上面是代码,使用的是mysql数据库,表是自己建的学生姓名表测试,数据库50例题的数据库
使用了.dataGridView1控件,这控件本来可以直接链接数据库,不用手动写入数据的,但是我的直接链接没做成,只好手动写入数据按照数据库结构一一进行写入
写入中发现没对列进行设置,试图在代码中创建,还是报错,原来是要在窗体里面手动设置好,然后成功。
using System;
using MySql.Data.MySqlClient;
namespace WinFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
readdatabase();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void readdatabase()
{
String connetStr = "server=127.0.0.1;port=3306;user="密码";password=root; database=student;";
MySqlConnection conn = new MySqlConnection(connetStr);
try
{
conn.Open();
string sql = "select * from student";
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("s_id");
this.dataGridView1.Rows[index].Cells[1].Value = reader.GetString("s_name");
this.dataGridView1.Rows[index].Cells[2].Value = reader.GetString("s_birth");
this.dataGridView1.Rows[index].Cells[3].Value = reader.GetString("s_sex");
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}