C#实现mysql数据库连接
一、功能实现
1、设计一个项目连接到自己的MySQL数据库,数据库包含至少三张表;
2、使用dataGridView控件显示表中的数据;
3、实现基本crud操作;
二、相关驱动配置
点击工具→NuGet包管理器→管理解决方案……
浏览搜索mysql,下载MySQL.Data到当前项目
三、具体功能实
简单CRUD实现
1.窗体显示
添加dataGridView和button控件如下
2.相关代码
全局变量定义
MySqlConnection x;
MySqlDataAdapter mda;
DataSet ds;
相关控件代码
1.“数据库连接”控件
private void button1_Click(object sender, EventArgs e) {
string M_str_sqlcon = "server=localhost;
user id=用户名;
password=密码;
database=使用的数据库";
x = new MySqlConnection(M_str_sqlcon);
try {
conn.Open();
MessageBox.Show("数据库连接成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
2.“查询”控件
private void button3_Click(object sender, EventArgs e) {
string sql = "select * from student";
mda = new MySqlDataAdapter(sql, x);
ds = new DataSet();
mda.Fill(ds, "student");
dataGridView1.DataSource = ds.Tables["student"];
x.Close();
}
3.“删除”控件
private void button6_Click(object sender, EventArgs e)
{
int index = dataGridView1.CurrentCell.RowIndex;
int id =(int) dataGridView1.Rows[index].Cells[0].Value;
string sql = "delete from student where id="+id+"";
x.Open();
MySqlCommand cmd = x.CreateCommand();
cmd.CommandText = sql;
int i = cmd.ExecuteNonQuery();
if (i < 0)
{
conn.Close();
MessageBox.Show("删除失败");
return;
}
x.Close();
}
4."增加"控件
private void button5_Click(object sender, EventArgs e)
{
if (mda == null || ds == null)
{
MessageBox.Show("导入数据");
return;
}
try
{
string msg = "是否确定该条数据的添加?";
if (1 == (int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
{
MySqlCommandBuilder builder = new MySqlCommandBuilder(mda);
mda.Update(ds, "student");
MessageBox.Show("添加成功", "提示");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "错误信息");
}
}
5."修改"控件
private void button4_Click(object sender, EventArgs e)
{
if (mda == null || ds == null)
{
MessageBox.Show("导入数据");
return;
}
try
{
string msg = "是否确认修改?";
if (1 == (int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
{
MySqlCommandBuilder builder = new MySqlCommandBuilder(mda); //命令生成器。
//适配器会自动更新用户在表上的操作到数据库中
mda.Update(ds, "student");
MessageBox.Show("修改成功", "提示");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "错误信息");
}
}
3.成果展示
数据库连接
查询所有表格
数据修改
修改前
修改后
数据添加
添加前
添加后
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_53850212/article/details/124976830