一、建立mysql数据库连接
安装NUget包
引用mysql驱动包
建立通讯
//创建一个连接字符串
string connectsql="server=localhost;database=water;user=root;password=123456;";//创建连接对象
MySqlConnection conn = new MySqlConnection(connectsql);//打开连接
二、建立查询,本次采用datagridview表格显示
建立如上的控件。
核心代码如下:
private void button1_Click(object sender, EventArgs e)
{
//创建一个连接字符串
string connectsql = "server=localhost;database=water;user=root;password=123456;";//创建连接对象
MySqlConnection conn = new MySqlConnection(connectsql);//打开连接
try
{
conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句
MessageBox.Show("已经建立连接");
//在这里使用代码对数据库进行查询dateTimePicker1
string start_date = dateTimePicker1.Value.ToString();
string end_date = dateTimePicker2.Value.ToString();
textBox5.Text = start_date;
textBox6.Text = end_date;
textBox7.Text = "select xh,tt,t1,t2,t3 from tt1 where tt BETWEEN '" + start_date + "' and '"+end_date+"'order by xh";
//textBox7.Text = "select xh,tt,t1,t2,t3 from tt1 where tt BETWEEN '2023-12-29 17:10:00' and '2023-12-29 23:12:01'";
string sql = textBox7.Text;
this.dataGridView1.Rows.Clear();//初始化清空数据
this.dataGridView1.Refresh();//刷新数据
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.GetInt32("xh").ToString();
this.dataGridView1.Rows[index].Cells[1].Value = reader.GetDateTime("tt").ToString();
this.dataGridView1.Rows[index].Cells[2].Value = reader.GetFloat("t1").ToString();
this.dataGridView1.Rows[index].Cells[3].Value = reader.GetFloat("t2").ToString();
this.dataGridView1.Rows[index].Cells[4].Value = reader.GetFloat("t3").ToString();
}
}
finally
{
conn.Close();// 关闭连接
}
}
三、测试效果
|