一、实验目的

1、请设计一个项目连接到自己的MySQL数据库,数据库包含至少三张表;
2、使用dataGridView控件显示表中的数据;
3、实现基本crud操作;

二、具体操作

1.数据库连接VS2019

(1)下载mysql 的驱动

要不然在VS中连接数据库时会发现没有mysql数据库。

下载驱动:
mysql-connector-odbc-8.0.20-winx64.msi
mysql odbc驱动


mysql-for-visualstudio-1.2.9.msi
Visual Studio连接MySQL工具


mysql-connector-net-8.0.20.msi
mysql数据库.net开发驱动
 

(2)连接数据库

step1: 点击视图,选择 服务器资源管理器

step2:右击数据连接,选择添加连接

step3:这个时候会发现,数据源中出现了MYSQL Database的选项,选择它

 step4:填上合适的数据库信息(就是你提前创建的数据库的信息)

              Server name输入MySQL的IP地址
              localhost即本地,localhost=127.0.0.1
              一般我们直接选择本地输入localhost或者127.0.0.1
              然后输入MySQL的用户名和密码
              Database name输入test(可自行选择)

 step5:可以点击测试链接,如果显示测试成功,就可以点击确定,完成连接;

 2.建表

这里可以选择可以直接打开navicat在数据库中建表,但是由于我已经提前建好,所以我就不在此演示了

3.使用DataGridView控件显示表中的数据

step1:在工具箱中检索DataGridView控件,拖拽到窗体中

一定要注意,进行这个操作前,去看看这个数据链接是不是打开的状态,如果你是重新启动去看的,那么就是关闭的状态,你去点击一下就可以打开了!!!然后进行以下操作:

 

step2:点击选择数据源旁边的小箭头,选择添加数据源

 step3:选择你的数据库类型,一步一步跟着图片走即可

 

 

step4:最后就是选择你想要绑定的表格就完成了!

 4.实现基本crud操作(具体代码)

(1)基本操作

private void print_in_dataGridView()
        {
            MySqlCommand mycom = conn.CreateCommand();
            mycom.CommandText = "SELECT * FROM student ; ";
            MySqlDataAdapter adap = new MySqlDataAdapter(mycom);
            DataSet ds = new DataSet();
            adap.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0].DefaultView;
        }
 
        private void button5_Click(object sender, EventArgs e)
        {
            string M_str_sqlcon = "server=localhost;user id=root;password=20010401;database=test";                                                                                              //创建数据库连接对象
            conn = new MySqlConnection(M_str_sqlcon);
            try
            {
                //打开数据库连接
                conn.Open();
                MessageBox.Show("数据库已经连接了!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            print_in_dataGridView();
        }

 (2)增


private void button4_Click(object sender, EventArgs e)
        {
            String table_name = textBox1.Text.Trim();
            String Id = textBox2.Text.Trim();
            String Name = textBox3.Text.Trim();
            String Sex = textBox4.Text.Trim();
            String Birth = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            string[] row = { Id, Name, Birth, Sex };
 
            try
            {
                conn.Open();
                String insertstr = "INSERT INTO Student (s_id,s_name,s_birth,s_sex) VALUES" + "(" + Id + "," + Name + "," + Birth + "," + Sex + ");";
                MySqlCommand cmd = new MySqlCommand(insertstr, conn); //实例化数据库命令对象
                cmd.ExecuteNonQuery(); //执行命令
            }
            catch { MessageBox.Show("输入数据有误,请输入有效数据!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            finally { conn.Close(); }
            //显示到dataGridView
            print_in_dataGridView();

         }

 (3)删:

private void button3_Click(object sender, EventArgs e)
        {
        try
                    {
                        conn.Open();
                        string select_id = textBox2.Text;//选择的当前行第一列的值,也就是ID
                        string delete_by_id = "delete from Student where s_id = " + "\"" + select_id + "\"";//sql删除语句,根据学号删除
                        MySqlCommand cmd = new MySqlCommand(delete_by_id, conn);
                        cmd.ExecuteNonQuery(); //执行命令
                    }
                    catch { MessageBox.Show("请正确选择行!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); }
                    finally { conn.Dispose(); }
                    print_in_dataGridView();
        }

(4)改:

private void button2_Click(object sender, EventArgs e)
        {
            int flag1 = 0, flag2 = 0;
            try
            {
                conn.Open();//打开数据库
                string updatestr = "UPDATE Student SET ";
                String table_name = textBox1.Text.Trim();
                String Id = textBox2.Text.Trim();
                String Name = textBox3.Text.Trim();
                String Sex = textBox4.Text.Trim();
                String Birth = dateTimePicker1.Value.ToString("yyyy-MM-dd");
                string[] row = { Id, Name, Birth, Sex };
                
                if (checkBox_birth.Checked == true)
                {
                    if (flag1 == 0)
                    {
                        updatestr += "s_birth = " + "\"" + Birth + "\"";
 
                        flag1 = 1;
 
                    }
                    else
                        updatestr += ", s_birth = " + "\"" + Birth + "\"";
                }
                if (checkBox_name.Checked == true)
                {
                    if (flag1 == 0)
                    {
                        updatestr += "s_name = " + "\"" + Name + "\"";
                        flag1 = 1;
                    }
                    else
                        updatestr += ", s_name = " + "\"" + Name + "\"";
                }
                if (checkBox_sex.Checked == true)
                {
                    if (flag1 == 0)
                    {
                        updatestr += "s_sex = " + "\"" + Sex + "\"";
                        flag1 = 1;
                    }
                    else
                        updatestr += ", s_sex = " + "\"" + Sex + "\"";
                }
                updatestr += " WHERE s_id = " + "\"" + Id + "\"";
                MySqlCommand cmd = new MySqlCommand(updatestr, conn);
                cmd.ExecuteNonQuery();
            }
            catch
            {
                flag2 = 1;
                MessageBox.Show("输入数据违反要求!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally { conn.Close(); }
 
            print_in_dataGridView();
            if (flag2 == 0)
            {
                MessageBox.Show("修改成功!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

 (5)查:

private void button1_Click(object sender, EventArgs e)
        {
            string table_name = textBox1.Text.Trim();
            string name = textBox3.Text.Trim();
            string date = dateTimePicker1.Text;
            string sex = textBox4.Text.Trim();
            if (table_name == null && (table_name != "教师") && (table_name!="学生"))
 
            {
                MessageBox.Show("请正确填写表格名");
            }
 
            else
            {
                
                string sql = "select * from " + table_name;
                mda = new MySqlDataAdapter(sql, conn);
                ds = new DataSet();
                mda.Fill(ds, table_name);
                //显示数据
                dataGridView1.DataSource = ds.Tables[table_name];
                conn.Close();
 
            }
 
        }

三、实验结果

数据库查询:

 数据修改:

四、仓库代码

https://gitee.com/ajiuooo/csharp-for-database-connection.git

Logo

本社区面向用户介绍CSDN开发云部门内部产品使用和产品迭代功能,产品功能迭代和产品建议更透明和便捷

更多推荐