>效果: 基于前面的程序 S7-200 Smart读取温湿度控制器,测试c#
增加一个按钮,链接access数据库,将数据定时记录到access数据库 private void btn_connect_Click(object sender, EventArgs e)//连接数据库 { using (OleDbConnection connection = new OleDbConnection(connectionString)) { try { connection.Open(); MessageBox.Show("数据库连接成功"); update_timer.Enabled = true; btn_connect.BackColor=Color.Green; btn_connect.Text = "数据库已连接"; DateTime now = DateTime.Now; string dateString = now.ToString("yyyy-MM-dd HH:mm:ss"); if (this.WD.Text == "") { MessageBox.Show("插入数据不能为空"); } else { string reg = "insert into data(日期时间,温度,湿度) values('" + dateString + "','" + this.WD.Text + "','" + this.SD.Text + "')"; OleDbCommand cmd = new OleDbCommand(reg, connection); cmd.CommandText = reg; cmd.ExecuteNonQuery(); MessageBox.Show("数据添加成功"); } } catch (Exception ex) { MessageBox.Show("数据库连接失败" + ex.Message); } } } private void timer2_Tick(object sender, EventArgs e)//定时插入数据库 { using (OleDbConnection connection = new OleDbConnection(connectionString)) { try { connection.Open(); DateTime now = DateTime.Now; string dateString = now.ToString("yyyy-MM-dd HH:mm:ss"); if (this.WD.Text == "") { MessageBox.Show("插入数据不能为空"); } else { string reg = "insert into data(日期时间,温度,湿度) values('" + dateString + "','" + this.WD.Text + "','" + this.SD.Text + "')"; OleDbCommand cmd = new OleDbCommand(reg, connection); cmd.CommandText = reg; cmd.ExecuteNonQuery(); } } catch (Exception ex) { MessageBox.Show("数据库连接失败" + ex.Message); } } }
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |