求助論壇各位大神,用C#寫了一個串口程式,想將接收到的串口資料寫入進資料庫,可以成功寫入。但是存在一個問題,接收一條資料在資料庫中顯示出兩條一樣的記錄,本人剛剛學習C#,接觸編程,不知道問題出現在哪里,還請各位大神指出錯誤。下面貼出接收事件原始碼。
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// string readString = serialPort1.ReadExisting();
// this.Invoke(updateText, new string[]{ readString });
int num = serialPort1.BytesToRead;
byte[] received_buf = new byte[num];
receive_count += num;
serialPort1.Read(received_buf, 0, num);
sb.Clear();
foreach (byte b in received_buf)
{
sb.Append(b.ToString("X2") + ' ');
}
this.Invoke((EventHandler)(delegate
{
string time = Convert.ToString(System.DateTime.Now);
textBox2.AppendText(sb.ToString());
textBox4.Text = "Rx:" + receive_count.ToString() + "Bytes";
textBox6.Text = time;
string sqlstr = "server=MS-LULZHXBCECCP;user Id=wl;Pwd=123;DataBase=chuankou";
SqlConnection con = new SqlConnection(sqlstr);
con.Open();
string ckdata = textBox2.Text.Trim();
string cktime = textBox6.Text.Trim();
string sqltianjia = "insert into jieshou(shijian,shuju)values('" + cktime + "','" + ckdata + "')";
SqlCommand comm = new SqlCommand(sqltianjia, con);
int i= comm.ExecuteNonQuery();
if(i==1)
{
textBox5.Text="添加成功";
}
else
{
textBox5.Text="添加失敗";
}
con.Close();
} ) );
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/225215.html
標籤:C#
