我的列表框上有3个元素(脉率,氧气水平,日期/时间)。正在从COM端口读取列表框中的数据。我想将这3个元素插入到数据库表的3个不同字段中。我怎么做?
int numberOfBytesToRead = 125;
if (bBuffer.Count >= numberOfBytesToRead)
{
this.Invoke(new Action(() =>
listBox1.Items.Add("SP: " + (bBuffer[43].ToString()) + " " + " HR: "
+ bBuffer[103].ToString() +" " + " Time: " + DateTime.Now.ToString())
));
bBuffer.RemoveRange(0, numberOfBytesToRead);
}
string strConnString = ConfigurationManager.ConnectionStrings["BMS.Properties.Settings.BMS"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnString);
try
{
string strCmd = "INSERT INTO DimRecords ( PulseRate, OxygenLevel, PatientID, DateOfMonitoring) ";
strCmd += " VALUES ( @PR, @OL, @ID, @Date)";
SqlCommand cmd = new SqlCommand(strCmd, myConnect);
cmd.Parameters.AddWithValue("@PR", listBox1.Text );
cmd.Parameters.AddWithValue("OL",listBox1.Text );
cmd.Parameters.AddWithValue("@ID", labelID.Text );
cmd.Parameters.AddWithValue("@Date",listBox1.Text );
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Data Inserted");
}
else
{
MessageBox.Show("Error!");
}
myConnect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
答案 0 :(得分:1)
您需要像这样的查询
//for update
update table set column1=val,column2= value, column3= value wherer condition
//for insert data
Insert into tablename values(val1,val2,val3)
答案 1 :(得分:1)
将您的代码修改为:
int numberOfBytesToRead = 125;
if (bBuffer.Count >= numberOfBytesToRead)
{
this.Invoke(new Action(() =>
listBox1.Items.Add(string.Format("SP: {0}, HR: {1}, Time: {2}",
bBuffer[43].ToString(),
bBuffer[103].ToString(),
DateTime.Now.ToString()
))));
bBuffer.RemoveRange(0, numberOfBytesToRead);
}
.....
foreach (var item in listBox1.Items)
{
InsertToDatabase(item.ToString());
}
private void InsertToDatabase(string input)
{
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BMS.Properties.Settings.BMS"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
string[] items = input.Split(new char[]{':',','},StringSplitOptions.RemoveEmptyEntries);
string sp = items[1];
string hr = items[3];
string time = items[5];
conn.Open();
cmd.CommandText = @"INSERT INTO DimRecords (PulseRate,OxygenLevel,PatientID,DateOfMonitoring)
VALUES (@PR,@OL,@ID,@Date)";
cmd.Parameters.AddWithValue("@PR", hr);
cmd.Parameters.AddWithValue("@OL", sp);
cmd.Parameters.AddWithValue("@ID", labelID.Text);
cmd.Parameters.AddWithValue("@Date", time);
int result= cmd.ExecuteNonQuery().ToString();
}
MessageBox.Show((result > 0) ? "Data Inserted" : "Error");
}