C#连接mysql,用dataGridView控件显示数据,实现基本的CRUD

1.C#连接mysql

准备工作

下载驱动:
mysql-for-visualstudio-1.2.9.msi Visual Studio 连接MySQL工具
mysql-connector-net-8.0.20.msi mysql             数据库.net开发驱动

2022版本的VS

可以点击工具

 点击第二个选项

下载

配置好后,单击视图,点击服务器资源管理器,右击数据连接,点击添加连接

Server name(localhost) 是服务器名称 user name是用户ID Passwords是用户密码

单击测试连接

连接成功后,可以查看数据库中的数据。

2.用dataGridView控件显示数据,实现基本的CRUD

添加六个button控件,一个datagridview控件,调整合适的大小。

然后为按钮编写相应的事件。

首先设置三个全局变量

  MySqlConnection conn; //连接数据库对象
        MySqlDataAdapter mda; //适配器变量
        DataSet ds;  //临时数据集

增加

private void button1_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 button2_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(), "错误信息");
            }
        }

 查询(其中的sql查询语句可以根据需要自行设置)

 private void button4_Click(object sender, EventArgs e)
        {
            string sql = "select * from student";
            mda = new MySqlDataAdapter(sql, conn);
            ds = new DataSet();
            mda.Fill(ds, "student");
            //显示数据
            dataGridView1.DataSource = ds.Tables["student"];
            conn.Close();
        }

连接数据库:

private void button5_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);
            }
        }

退出

  private void button6_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

完整代码:

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Windows数据库连接
{
    public partial class Form1 : Form
    {
        MySqlConnection conn; //连接数据库对象
        MySqlDataAdapter mda; //适配器变量
        DataSet ds;  //临时数据集
                     //这三个全局定义

        public Form1()
        {
            InitializeComponent();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string M_str_sqlcon = "server=localhost;user id=root;password=20010314hu.;database=实验二";                                                                                              //创建数据库连接对象
            conn = new MySqlConnection(M_str_sqlcon);
            try
            {
                //打开数据库连接
                conn.Open();
                MessageBox.Show("数据库已经连接了!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string sql = "select * from student";
            mda = new MySqlDataAdapter(sql, conn);
            ds = new DataSet();
            mda.Fill(ds, "student");
            //显示数据
            dataGridView1.DataSource = ds.Tables["student"];
            conn.Close();
        }

        private void button1_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 button2_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(), "错误信息");
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

运行结果:

单击连接数据库

单击查询

 单击修改

同理,可依次实现增删改查相关操作。

Gitee仓库地址:https://gitee.com/xiaohutongxue80/windows.git

  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值