数据来自串口,但数据库没有更新

时间:2017-05-21 13:04:29

标签: c# database serial-port

数据是从serial port接收但未与声明字符串进行比较,我想更新数据库中记录表中的unit_consumed字段。 while循环也在工作。我想知道串行数据如何与字符串进行比较,然后更新数据库字段。

  int unit = 0;
        string s = "unit_consumed";
        SerialPort myport = new SerialPort();
        myport.BaudRate = 9600;
        myport.PortName = "COM4";
        myport.Open();
        while(true)
        {
            string data_rx = myport.ReadLine();
            File.AppendAllText("test_file.txt", data_rx + "\n");
            unit = unit + 1;
            if (string.Equals(data_rx,s))
            {
                SqlConnection con = new SqlConnection("Data Source=MIAN\\SQLEXPRESS;Initial Catalog=arduino;Integrated Security=True");
                con.Open();
                SqlCommand cmd = new SqlCommand("insert into record(unit_consumed) values(@unit_consumed) ", con);
                cmd.Parameters.AddWithValue("@unit_consumed", unit);
                con.Close();
            }
            Console.WriteLine(data_rx);

1 个答案:

答案 0 :(得分:0)

您没有执行查询。

尝试:

SqlConnection con = new SqlConnection("Data Source=MIAN\\SQLEXPRESS;Initial Catalog=arduino;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("insert into record(unit_consumed) values(@unit_consumed) ", con);
cmd.Parameters.AddWithValue("@unit_consumed", unit);

// ********** need to execute 
cmd.ExecuteNonQuery();

con.Close();