C#-连接mysql数据库和C#展示数据表
C#连接mysql数据库
https://www.cnblogs.com/my---world/p/12044302.html
C#展示数据表
http://c.biancheng.net/view/3037.html
例如:
//查询全部课程 private void QueryAllCourse() { String connetStr = "server=127.0.0.1;port=3306;user=root;password=root; database=test;"; //usr:用户名,password:数据库密码,database:数据库名 MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句 Console.WriteLine("已经建立连接"); string sql = "select * from course"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象 // 表格清空 int countOld = dataGridView1.RowCount; if (countOld > 0) { for (int i = 0; i < countOld; i++) { dataGridView1.Rows.Clear(); } } //表格填充 while (reader.Read()) { int index = this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[0].Value = reader.GetString("id"); this.dataGridView1.Rows[index].Cells[1].Value = reader.GetString("name"); this.dataGridView1.Rows[index].Cells[2].Value = reader.GetString("credit"); this.dataGridView1.Rows[index].Cells[3].Value = reader.GetString("remark"); } //设置数据表格上显示的列标题 dataGridView1.Columns[0].HeaderText = "id"; dataGridView1.Columns[1].HeaderText = "课程名称"; dataGridView1.Columns[2].HeaderText = "学分"; dataGridView1.Columns[3].HeaderText = "备注"; //设置数据表格为只读 dataGridView1.ReadOnly = true; //不允许添加行 dataGridView1.AllowUserToAddRows = false; //背景为白色 dataGridView1.BackgroundColor = Color.White; //只允许选中单行 dataGridView1.MultiSelect = false; //整行选中 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } catch (MySqlException ex) { Console.WriteLine(ex.Message); MessageBox.Show("出现错误!" + ex.Message); } finally { //关闭数据库连接 conn.Close(); } }