运行我的应用程序时会出现此问题。 Express Profiler显示与数据库的连接出现两次,因此代码中存在问题!
代码示例我在这里定义要发送的内容。
label_Map.Text = message.Substring(21, 3);
label_Sys.Text = message.Substring(15, 3);
label_Dia.Text = message.Substring(18, 3);
label_Pulse.Text = message.Substring(26, 3);
//System.IO.File.WriteAllText(@"D:\String.txt", label_Sys.Text);
//System.IO.File.WriteAllText(@"D:\String.txt", label_Dia.Text);
//System.IO.File.WriteAllText(@"D:\String.txt", label_Pulse.Text);
SaveData(
message.Substring(15, 3),
message.Substring(18, 3),
message.Substring(26, 3)
//label_Sys.Text,
//label_Dia.Text,
//label_Pulse.Text
并在此处发送代码
private void SaveData(string sys, string dia, string pulse)
{
try
{
string connectionString = @"Data Source=PlUTO-PC\;Initial Catalog=merisana;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
// connection.Open();
string queryString = "INSERT INTO dbo.merisana_test (sys, dia, pulse) VALUES (@sys, @dia, @pulse)";
SqlCommand command = new SqlCommand(queryString, connection);
//command.CommandText = string.Format("INSERT INTO merisana1 (sys, dia, pulse) VALUES ({0}, {1}, {2})", sys, dia, pulse);
command.Parameters.AddWithValue("@sys", sys);
command.Parameters.AddWithValue("@dia", dia);
command.Parameters.AddWithValue("@pulse", pulse);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
完整代码https://www.dropbox.com/s/4oitl0p3ldcfo79/Form1.cs?v=0swn-
答案 0 :(得分:1)
您需要调试此代码:
string buffer = "";
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (serialPort1.BytesToRead > 0)
{
buffer += serialPort1.ReadTo("\r");
int index1 = buffer.IndexOf('\u0002');
int index2 = buffer.IndexOf('\u0003', index1 + 1);
string buf = "";
if ((index1 >= 0) && (index2 > index1))
{
buf = buffer.Substring(index1 + 1, (index2 - 1 - index1));
buffer = buffer.Remove(index1, (index2 - index1));
this.BeginInvoke(new displayDeleg(display), new object[] { buf });
}
}
}
您正在从显示方法调用您的保存方法,显然,由于您处于while循环中,因此可以多次调用此方法。
答案 1 :(得分:0)
100%确定您正在调用该方法两次,尝试发布您的正面代码。
从代码behing你只是调用一次,但也许按钮的行为使它发生两次。
此外,在为数据库查询创建函数时,尝试返回int而不是make it void,这样您就可以跟踪这些事情了。
另外,设置断点并查看您拨打SaveData
想把它作为评论,但我不能,抱歉