ADO.NET连接MySQL并绑定DataGridView

ADO.NET

ADO.NET组件的目的是为了从数据操作中分解出数据访问。
ADO.NET有两大核心组件:DataSet和.NET数据提供程序。
.NET数据提供程序包括Connection、Command、DataReader、DataAdapter。
DataSet是一种数据集合,包含多个DataTable对象的集合,DataTable由数据行、列、主键等信息组成。
Connection用来建立与数据库的连接。
Command用来对数据库的增删改查的操作。
DataReader用来查询数据库的多列、多条记录。
DataAdapter是DataSet和数据库连接之间的桥接器。

实例

本文将结合一个实例介绍如何使用DataGridView控件操作MySQL数据库中的数据。
首先,在设计界面设计一个DataGridView控件,并设置其属性以及各列的属性,(name)为dataGridView1。
在DataGridView的列编辑器可以设置列的属性,如下图。
1
每一列的DataProperty属性要与数据库中的字段名相同。
使用DataGridView.DataSource为其设置绑定的数据源,然后分别在事件CellBeginEdit和事件CellEndEdit编辑代码,用来更新修改数据。
使用TextBox、ComboBox和Button三个控件来查询数据。

用NuGet安装上MySql.Data:
1

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 WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.DataSource = GetDataTable("");
            this.comboBoxCondition.SelectedIndex = 0;
        }

        DataSet dataSet;
        MySqlDataAdapter mySqlDataAdapter;
        object oldValues;
        string connStr = "server=localhost;Database=pikachu;uid=root;pwd=root;charset=utf8";

        private DataTable GetDataTable(string sqlStr)
        {
            using (MySqlConnection conn = new MySqlConnection(connStr))
            {
                mySqlDataAdapter = new MySqlDataAdapter();
                // string sql = @"SELECT [id], [username] FROM [pikachu].[users] WHERE 1=1";
                string sql = @"SELECT id, username FROM users WHERE 1=1 ";
                dataSet = new DataSet();
                mySqlDataAdapter.SelectCommand = new MySqlCommand(sql + sqlStr, conn);
                mySqlDataAdapter.Fill(dataSet);
            }
            return dataSet.Tables[0];
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            oldValues = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string condition = this.dataGridView1.CurrentRow.Cells[e.ColumnIndex].Value.ToString();

            if (oldValues.ToString() == condition)
                return;

            DialogResult result = MessageBox.Show("确定要保存对数据的修改吗?", "提示", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Question);
            if(result == DialogResult.OK)
            {
                MySqlConnection mySqlConnection = new MySqlConnection(connStr);
                mySqlDataAdapter.UpdateCommand = mySqlConnection.CreateCommand();
                string sql = string.Empty;
                switch(e.ColumnIndex)
                {
                    case 1:
                        sql = string.Format("username='{0}'", condition);
                        break;
                    default:
                        break;
                }
                string id = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
                sql = string.Format("update users set {0} where id = {1}", sql, id);

                mySqlDataAdapter.UpdateCommand.CommandText = sql;
                MySqlCommandBuilder mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
                mySqlDataAdapter.Update(dataSet, dataSet.Tables[0].TableName);
                MessageBox.Show("修改成功!");
            }
            else
            {
                this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = oldValues;
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            string condition = this.txtCondition.Text.Trim();
            string sql = string.Empty;
            int index = this.comboBoxCondition.SelectedIndex;

            switch (index)
            {
                case 0:
                    sql = string.Format("and id = {0}", condition);
                    break;
                case 1:
                    sql = string.Format("and username like '%{0}%'", condition);
                    break;
                default:
                    sql = string.Format("and username like '%{0}%'", condition);
                    break;
            }
            this.dataGridView1.DataSource = GetDataTable(sql);
        }
    }
}

效果如下:
1

参考

https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.datagridview?view=windowsdesktop-6.0

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小龙在山东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值