开发环境:VS2010
数据库:MySQL V5.5.42
连接器:Connector.NET V6.9
1. 新建工程(Windows Application)
2. 增加引用(MySql.Data)
3. 放置控件
1个TextBox,1个DataGrideView等等
4. 查询按钮事件
private void btnSearch_Click(object sender, EventArgs e) { string connStr = string.Format( "server={0}; user id={1}; password={2}; database=test; pooling=false", "localhost", "root", "qaz1xsw2"); try { conn = new MySqlConnection(connStr); conn.Open(); } catch (MySqlException ex) { MessageBox.Show("没有找到数据库: " + ex.Message); } // 设置数据桥 dataAdapter = new MySqlDataAdapter( edtSql.Text, conn); // SQL sqlCmdBuilder = new MySqlCommandBuilder(dataAdapter); // 建立数据表 table = new DataTable(); DataSet ds = new DataSet(); // 填充数据到数据桥 dataAdapter.Fill(ds); DataColumn dc = new DataColumn(); dc.ColumnName = "序号"; dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; table.Columns.Add(dc); table.Merge(ds.Tables[0]); // 指定数据源 dataGridView1.DataSource = table; }
运行效果
源代码:
Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace WindowsFormsApplication2 { public partial class Form1 : Form { private MySqlConnection conn; private DataTable table; private MySqlDataAdapter dataAdapter; private MySqlCommandBuilder sqlCmdBuilder; public Form1() { InitializeComponent(); } private void btnSearch_Click(object sender, EventArgs e) { string connStr = string.Format( "server={0}; user id={1}; password={2}; database=test; pooling=false", "localhost", "root", "qaz1xsw2"); try { conn = new MySqlConnection(connStr); conn.Open(); } catch (MySqlException ex) { MessageBox.Show("没有找到数据库: " + ex.Message); } // 设置数据桥 dataAdapter = new MySqlDataAdapter( edtSql.Text, conn); // SQL sqlCmdBuilder = new MySqlCommandBuilder(dataAdapter); // 建立数据表 table = new DataTable(); DataSet ds = new DataSet(); // 填充数据到数据桥 dataAdapter.Fill(ds); DataColumn dc = new DataColumn(); dc.ColumnName = "序号"; dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; table.Columns.Add(dc); table.Merge(ds.Tables[0]); // 指定数据源 dataGridView1.DataSource = table; } } }
参考文章:《MySQL
Connector/Net 的简单使用》
时间: 2024-11-09 05:56:46