首先,您确实应该使用 using 语句,以便在发生异常时关闭连接
using(SqlConnection con = new SqlConnection("**********************************************"))
using(SqlCommand cmd = con.CreateCommand()) //The create command can happen before the open
{
con.Open();
cmd.CommandText = "INSERT INTO Borrowbook ([Student ID], ISBN, Title, Date) VALUES ( @StudentID, @ISBN , @Title, @Date)";
//(Snip adding parameters)
cmd.ExecuteNonQuery();
//You don't need to call close if you are using "using"
}
顺便说一句,有三种方法可以做到这一点。
您可以将两个命令放在一个命令语句中。
using(SqlConnection con = new SqlConnection("**********************************************"))
using(SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"INSERT INTO Borrowbook ([Student ID], ISBN, Title, Date) VALUES ( @StudentID, @ISBN , @Title, @Date);
INSERT INTO StudentActvitiy ([Student ID], Date) VALUES ( @StudentID, GETDATE())";
//(Snip adding parameters)
cmd.ExecuteNonQuery();
}
或者您可以更改命令文本并再次运行它
using(SqlConnection con = new SqlConnection("**********************************************"))
using(SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "INSERT INTO Borrowbook ([Student ID], ISBN, Title, Date) VALUES ( @StudentID, @ISBN , @Title, @Date)";
//(Snip adding parameters)
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO StudentActvitiy ([Student ID], Date) VALUES ( @StudentID, GETDATE())"
cmd.ExecuteNonQuery();
}
或者你可以做两个命令
using(SqlConnection con = new SqlConnection("**********************************************"))
using(SqlCommand cmd = con.CreateCommand())
using(SqlCommand cmd2 = con.CreateCommand())
{
con.Open();
cmd.CommandText = "INSERT INTO Borrowbook ([Student ID], ISBN, Title, Date) VALUES ( @StudentID, @ISBN , @Title, @Date)";
//(Snip adding parameters)
cmd.ExecuteNonQuery();
cmd2.CommandText = "INSERT INTO StudentActvitiy ([Student ID], Date) VALUES ( @StudentID, GETDATE())"
SqlParameter p21 = new SqlParameter("@StudentID", SqlDbType.NChar);
p21.Value = textBox2.Text;
cmd2.Parameters.Add(p21);
cmd2.ExecuteNonQuery();
}
要做蒂姆的解决方案,它是第一个和第三个的组合。
using(SqlConnection con = new SqlConnection("**********************************************"))
using(SqlCommand cmd = con.CreateCommand())
using(SqlCommand cmd2 = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"INSERT INTO Borrowbook ([Student ID], ISBN, Title, Date) VALUES ( @StudentID, @ISBN , @Title, @Date);
SELECT CAST(SCOPE_IDENTITY AS INT);";
//(Snip adding parameters)
var resultId = (int)cmd.ExecuteScalar();
cmd2.CommandText = "INSERT INTO StudentActvitiy ([Student ID], Date, BorrowBookId) VALUES ( @StudentID, GETDATE(), @borrowBookId)"
SqlParameter p21 = new SqlParameter("@StudentID", SqlDbType.NChar);
p21.Value = textBox2.Text;
cmd2.Parameters.Add(p21);
SqlParameter p22 = new SqlParameter("@borrowBookId", SqlDbType.Int);
p22.Value = resultId;
cmd2.Parameters.Add(p22);
cmd2.ExecuteNonQuery();
}