11,848
社区成员
发帖
与我相关
我的任务
分享
--我这里为测试,在 tempdb 中创建测试表,你实际使用不要放在 tempdb 库, 创建新库或放已有库。
USE tempdb
GO
IF OBJECT_ID('device_data') IS NOT NULL DROP TABLE device_data
GO
CREATE TABLE device_data(
logId INT IDENTITY(1,1) PRIMARY KEY,
deviceName NVARCHAR(20),
voltage DECIMAL(10,2),
electricCurrent DECIMAL(10,2),
addTime DATETIME DEFAULT(GETDATE())
)
GO
下面是 C# 写的 控制台程序:
using System;
using System.Data.SqlClient;
using System.Timers;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
//创建定时器
Timer timer = new Timer();
timer.Interval = 3 * 1000; //3秒一次
timer.AutoReset = true; //自动循环
timer.Enabled = true;
timer.Elapsed += Timer_Elapsed; //定时执行事件
timer.Start();
Console.Read();
}
private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
//构建数据的具体过程,由你自己去实现,这里用随机数代替
DeviceInfo info = new DeviceInfo()
{
DeviceName = "镇流器",
Voltage = new Random().Next(10, 12),
ElectricCurrent = 5 * new Random().NextDouble()
};
//插入数据
Insert(info);
}
private static void Insert(DeviceInfo info)
{
try
{
//下面的是插入 SQL Server 数据库, 如是其它类型库, 应适当修改
//连接串自己根据实际的实例名(或ip,端口)和数据库名,用户名、密码等修改
string connString = @"Data Source=.\sqlserver2014;Initial Catalog=tempdb;Integrated Security=True";
string sql = @"INSERT INTO device_data(deviceName,voltage,electricCurrent) VALUES(@deviceName,@voltage,@electricCurrent)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@deviceName", info.DeviceName);
cmd.Parameters.AddWithValue("@voltage", info.Voltage);
cmd.Parameters.AddWithValue("@electricCurrent", info.ElectricCurrent);
cmd.ExecuteNonQuery();
}
Console.WriteLine("Inserted: "+info.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class DeviceInfo
{
public string DeviceName { get; set; }
public double Voltage { get; set; }
public double ElectricCurrent { get; set; }
public override string ToString()
{
return string.Format("DeviceName:{0}\tVoltage:{1}\tElectricCurrent:{2}",this.DeviceName, this.Voltage, this.ElectricCurrent);
}
}
}