时间:2021-07-01 10:21:17 帮助过:13人阅读
这样我们就可以使用MySql.Data中的方法来连接数据库了,连接数据库代码如下:
String connetStr = "server=127.0.0.1;port=3306;user=root;password=123; database=vs;"; //usr:用户名,password:数据库密码,database:数据库名 MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句 Console.WriteLine("已经建立连接"); } catch (MySqlException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); }
如果连接数据库成功,我们就可以进行下面的操作了,取出数据并通过DataGridView展示出来了,代码如下:
String connetStr = "server=127.0.0.1;port=3306;user=root;password=123; database=vs;"; MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句 Console.WriteLine("已经建立连接");
string sql = "select * from salecar"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象 while (reader.Read()) { int index = this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[0].Value = reader.GetString("name"); this.dataGridView1.Rows[index].Cells[1].Value = reader.GetString("describe"); this.dataGridView1.Rows[index].Cells[2].Value = reader.GetString("price"); this.dataGridView1.Rows[index].Cells[3].Value = reader.GetInt32("salenumber"); } } catch (MySqlException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); }
这样我们就完成了C#窗体连接MySql并通过DataGridView展示数据,下面是效果图和全部代码:
全部代码:
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; using MySql.Data.MySqlClient; namespace WindowsFormsApp1 { public partial class Form3 : Form { public Form3() { InitializeComponent(); a(); } private void button1_Click(object sender, EventArgs e) { Form1 fm1 = new Form1(); this.Hide(); fm1.ShowDialog(); Application.ExitThread(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } public void a() { String connetStr = "server=127.0.0.1;port=3306;user=root;password=123; database=vs;"; MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句 Console.WriteLine("已经建立连接"); //在这里使用代码对数据库进行增删查改 string sql = "select * from salecar"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象 while (reader.Read()) { int index = this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[0].Value = reader.GetString("name"); this.dataGridView1.Rows[index].Cells[1].Value = reader.GetString("describe"); this.dataGridView1.Rows[index].Cells[2].Value = reader.GetString("price"); this.dataGridView1.Rows[index].Cells[3].Value = reader.GetInt32("salenumber"); } } catch (MySqlException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } } } }
效果:
数据库表:
C#窗体连接MySql并通过DataGridView展示数据
标签:span task ide 没有 展示 show mes win ini