这个简单的Winforms程序从串行连接读取输入。我正在尝试将接收到的数据发送到本地数据库以供以后检索。
但是,由于数据一直为空,因此似乎不能正确地将其插入数据库表中。运行该程序时我没有收到任何错误,其他一切都正常。下面是程序代码
public partial class Form1 : Form
{
private SerialPort myPort;
private string dataIn;
private DateTime dt;
private static string cnString = Properties.Settings.Default.Database1ConnectionString;
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True
private SqlConnection dbConnection = new SqlConnection(cnString);
private SqlDataAdapter adapter = new SqlDataAdapter();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
myPort.DataReceived += MyPort_DataReceived;
try
{
myPort.Open();
textBox1.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void MyPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(display_dataevent));
dataIn = myPort.ReadLine();
dt = DateTime.Now;
dbConnection.Open();
using (var insertCmd = new SqlCommand(@"INSERT INTO Measurements (Distance,DateTime) VALUES (@Distance,@DateTime)", dbConnection))
{
insertCmd.Parameters.Add("@Distance", SqlDbType.VarChar).Value = dataIn;
insertCmd.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = dt;
insertCmd.ExecuteNonQuery();
}
dbConnection.Close();
}
private void display_dataevent(object sender, EventArgs e)
{
dt = DateTime.Now;
string time = dt.Hour + ":" + dt.Minute + ":" + dt.Second;
textBox1.AppendText(time + "\t\t\t" + dataIn + "\n");
}
}
}
现在一切正常。连接字符串应该受到谴责。由于我只创建了一个数据库,因此我不太了解如何操作,因此我不知道从哪里可以得到不正确的字符串。
答案 0 :(得分:0)
谢谢大家,由于某些原因连接字符串错误
答案 1 :(得分:-1)
通过将SqlConnection和SqlCommand置于“ using”中来进行处理。
using(var dbConnection = new SqlConnection(cnString))
{
dbConnection.Open();
using(var insertCmd = new SqlCommand(@"INSERT INTO Measurements (Distance, DateTime) VALUES(@Distance, @DateTime)", dbConnection))
{
insertCmd.Parameters.Add("@Distance", SqlDbType.VarChar).Value = dataIn;
insertCmd.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = dt;
insertCmd.ExecuteNonQuery();
}
}
还要确保dataIn
的值可接受,并且您的连接字符串有效。我通过上面的调整尝试了您的代码,并成功了。
如果问题仍然存在,请查看db日志文件查看器中是否存在任何可能的错误:https://docs.microsoft.com/en-us/sql/relational-databases/logs/open-log-file-viewer?view=sql-server-ver15