我想使用C#更新contactInfo数据库。我需要从Windows窗体中插入(可能)多个人/紧急联系人。所以我将windows窗体上的文本框设置为等于变量以传递到我的查询中。我知道如何为每个连接创建一条记录,但我该怎么办呢?例如,如果提供了辅助紧急联系人,我怎样才能插入txt2fname,txt2lname,txt2phone1,txt2phone2中提供的数据?
SqlConnection con = new SqlConnection("ConnectionStringGoesHere")
{
SqlCommand cmd;
try
{
string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2) Values(@fname, @lname, @phone1, @phone2)";
cmd = new SqlCommand(emergencyContactInfo, con);
con.Open();
cmd.Parameters.AddWithValue("@fname", txt1fname);
cmd.Parameters.AddWithvalue("@lname", txt1lname);
cmd.Parameters.AddWithValue("@phone1", txt1phone1);
cmd.Parameters.AddWithvalue("@phone2", txt1phone2);
cmd.ExecuteNonQuery();
connection.Close()
}
}
答案 0 :(得分:1)
你只需要这样做......
string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2) Values(@fname, @lname, @phone1, @phone2)";
cmd = new SqlCommand(emergencyContactInfo, con);
con.Open();
cmd.Parameters.Add("@fname", SqlDbType.<Type>);
<Add the other parameters here>
...
cmd.Parameters["@fname"].Value = txt1fname
<Add parameters values here>
...
cmd.ExecuteNonQuery();
cmd.Parameters["@fname"].Value = txt2fname
<Add parameters values here>
...
cmd.ExecuteNonQuery();
connection.Close()
答案 1 :(得分:0)
试试这个:
string SqlString =@"Insert into mytable(f1,f2) values ('1','2'),
Insert into mytable(f1,f2) values ('3','4'),
Insert into mytable(f1,f2) values ('5','6'), ";
con.Execute(SqlString);
或类似的东西
SqlConnection con = new SqlConnection("ConnectionStringGoesHere")
string emergencyContactInfo = @"Insert Into econtactInfo(fname, lname, phone1, phone2) Values({0}, {1}, {2}, {3})";
con.Open();
for(....)
{
con.Execute(String.Format(emergencyContactInfo ,txt1fname,txt1lname,txt1phone1 txt1phone2));
}
connection.Close();