读书人

串口接收数据库插入有关问题

发布时间: 2013-02-25 10:23:36 作者: rapoo

串口接收,数据库插入问题,求助
串口接收代码:


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 = "";
}



ExecuteSQL代码如下:

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();
}


每次程序都能接收到数据,但是在插入数据库的时候只能插入2次,就不能插入了,只有关闭程序再打开,又能插入2次
第一次都会同时插入2条相同的数据

就这个问题,感谢各位大神了
[解决办法]
总觉得你执行SQL的条件很难懂:两个if,一个是用usingStr,一个是用insertStr,而前者又是根据后者生成的

读书人网 >C#

热点推荐