串口接收,数据库插入问题,求助
串口接收代码:
private static void DataReceviedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
insertStr += indata;
foreach (char ch in insertStr)
{
if (ch != 'E' && ch != 'S'&& ch != 'o')
{
usingStr += ch;
}
}
string RealName = "";
switch (usingStr)
{
case "2011072069\0":
RealName = "a";
break;
case "2010073065\0":
RealName = "b";
break;
case "2011072069":
RealName = "a";
break;
case "2010073065":
RealName = "b";
break;
default:
break;
}
if (usingStr.Length == 11 || usingStr.Length == 10)// && already == false
{
if (insertStr[0] == 'E')
{
string Sqlcom = "INSERT INTO tb_out(RealName, Num, Date) VALUES('" + RealName + "'," + "'" + usingStr + "', GetDate());";
ExecuteSQL(Sqlcom);
}
if (insertStr[0] == 'S')
{
string Sqlcom = "INSERT INTO tb_in(RealName, Num, Date) VALUES('" + RealName + "'," + "'" + usingStr + "', GetDate());";
ExecuteSQL(Sqlcom);
}
}
usingStr = "";
}
public static void ExecuteSQL(string SQLwords)
{
//执行插入、删除、更新的函数
string myConStr = "user id=sa; password=lzr666;";
myConStr += "Initial Catalog = AccessControl; Server=PC2012050719LFQ;";
myConStr += "Connect Timeout = 10";
SqlConnection myCon = new SqlConnection(myConStr);
myCon.Open();
SqlCommand myCom = new SqlCommand();
myCom.CommandType = CommandType.Text;
myCom.CommandText = SQLwords;
myCom.Connection = myCon;
try
{
myCom.ExecuteNonQuery();
}
catch
{
}
myCon.Close();
}