PLC论坛-全力打造可编程控制器专业技术论坛

 找回密码
 注册哦

QQ登录

只需一步,快速开始

微信扫码登录

查看: 78508|回复: 0

测试c#查询MYSQL数据库

[复制链接]
发表于 2024-5-11 10:52:26 | 显示全部楼层 |阅读模式
一、建立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();// 关闭连接

     }

    }

三、测试效果

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册哦

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册哦

本版积分规则

QQ|小黑屋|手机版|Archiver|PLC技术网-PLC论坛 ( 粤ICP备17165530号 )|网站地图

GMT+8, 2024-9-19 08:16 , Processed in 0.044654 second(s), 28 queries .

快速回复 返回顶部 返回列表