读书人

怎么将数据定时保存到数据库

发布时间: 2013-11-30 22:36:00 作者: rapoo

如何将数据定时保存到数据库
我实时读取标签的ID,及温度、湿度信息,想将标签ID、温度、湿度、读取时间每隔10分钟保存到数据库中一次,改如何编程?用的是C#语言编写WinForm应用,使用的是SQL Server数据库。
如果用到Timer控件,改如何具体编程呢?
同意
[解决办法]
1,用timer定时器,每10分钟执行一次
2、读取读取标签的ID,及温度、湿度信息
3、数据插入数据库

使用System.Timers.Timer类
System.Timers.Timer t = new System.Timers.Timer(600000);
t.Elapsed += new System.Timers.ElapsedEventHandler(Do_Elapsed);
t.AutoReset = true;
t.Enabled = true;


private static void Do_Elapsed(object sender, ElapsedEventArgs e)
{
Tosql();
}

[code=csharp]

puclic void Tosql()
{
string strCon = "Data Source=192.168.1.5;Initial Catalog=data;User ID=sa;Pwd=sa";
string sql = "INSERT INTO table([ID],温度,湿度)" +"VALUES('" + ID + "'" +",'" + 温度+ "'" +",'" + 湿度 + "')" ;
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
sqlconn.Open();
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.ExecuteNonQuery();
sqlconn.Close();
}
}

读书人网 >C#

热点推荐