数据库连接
一、功能说明与实验目标
1、请设计一个项目连接到自己的MySQL数据库,数据库包含至少三张表;
2、使用dataGridView控件显示表中的数据;
3、实现基本crud操作;
二、实验过程
1、在VS2022中安装相关的MYSQL工具包
- 打开一个项目;
- 工具 --> NUGet包管理器;
- 搜索mysql,安装第一个。
2、实现功能
1、请设计一个项目连接到自己的MySQL数据库
//导入命名空间
using MySql.Data.MySqlClient;
private void button1_Click(object sender, EventArgs e)
{
string M_str_sqlcon = "server=localhost;user id=root;password=密码;database=使用的数据库"; //创建数据库连接对象
conn = new MySqlConnection(M_str_sqlcon);
try
{
//打开数据库连接
conn.Open();
MessageBox.Show("数据库已连接。");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
2、使用dataGridView控件显示表中的数据;
3、实现基本crud操作
private void button2_Click(object sender, EventArgs e)
{
string sql = "select * from user";
mda = new MySqlDataAdapter(sql, conn);
ds = new DataSet();
mda.Fill(ds, "user");
//显示数据
dataGridView1.DataSource = ds.Tables["user"];
conn.Close();
}
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, "user");
MessageBox.Show("添加成功", "提示");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "错误信息");
}
}
private void button5_Click(object sender, EventArgs e)
{
int index = dataGridView1.CurrentCell.RowIndex;
int id =(int) dataGridView1.Rows[index].Cells[0].Value;
string sql = "delete from user where id="+id+"";
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
int i = cmd.ExecuteNonQuery();
if (i < 0)
{
conn.Close();
MessageBox.Show("删除失败");
return;
}
conn.Close();
}
private void button3_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, "user");
MessageBox.Show("修改成功", "提示");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "错误信息");
}
}
三、实验总结
- 使用using来调用mysql连接,这样使用完后可以自动关闭连接连接数据库,不用手动写关闭数据库的方法:“using MySql.Data.MySqlClient”;
- 在写连接字符串的时候要写很长一段,容易写SqlConnectionStringBuilder可以用来帮助我们生成连接字符串.这样就可以分开来写DataSourceInitialCatalog等等。