如何在一个连接中创建两个命令?

时间:2013-08-22 14:18:47

标签: sql-server ado.net system.data

例如,我希望INSERT数据库中的数据以及UPDATE另一个表。我的代码就像这样

SqlConnection con = new SqlConnection("**");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT Borrowbook VALUES (@StudentID, @ISBN, @Title, @Date)";
SqlParameter p1 = new SqlParameter("@StudentID", SqlDbType.NChar);
p1.Value = textBox2.Text;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("@ISBN", SqlDbType.NVarChar);
p2.Value = textBox4.Text;
cmd.Parameters.Add(p2);
SqlParameter p3 = new SqlParameter("@Title", SqlDbType.VarChar);
p3.Value = textBox3.Text;
cmd.Parameters.Add(p3);
SqlParameter p4 = new SqlParameter("@Date", SqlDbType.DateTime);
p4.Value = dateTimePicker1.Text;
cmd.Parameters.Add(p4);    
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("The books has been successfully borrowed!", 
    "Information ... ",
    MessageBoxButtons.OK, 
    MessageBoxIcon.Information, 
    MessageBoxDefaultButton.Button1);

4 个答案:

答案 0 :(得分:4)

首先,您应该使用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();
}

要做Tim's solution,它就是第一个和第三个的组合。

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

答案 1 :(得分:1)

你可以。在执行第二个命令之前,请不要关闭连接。

示例步骤:

  
      
  1. 创建新连接
  2.   
  3. 打开连接
  4.   
  5. 创建命令1
  6.   
  7. 将params添加到Command 1
  8.   
  9. 执行命令1
  10.   
  11. 创建命令2
  12.   
  13. 将params添加到Command 2
  14.   
  15. 执行命令2
  16.   
  17. 关闭连接
  18.   
  19. 处理项目
  20.   

答案 2 :(得分:1)

您可以执行以下操作

        SqlConnection cn = new SqlConnection("********");
        string stmt = "insert projects(projectname) values('" + name + "' )";
        string stmt1="update dept set deptid="+id;

        SqlCommand cmd = new SqlCommand(stmt, cn);
        sqlcommand cmd1=new sqlcommand(stmt1,cn);           

        cn.Open();
        cmd.ExecuteNonQuery();

        cmd1.ExecuteNonQuery();
        cn.close()

答案 3 :(得分:0)

当我看到这样的问题时,我几乎总是问,“为什么你不使用存储过程?”您可以避免额外的往返数据库服务器。封装事务逻辑更容易,它是强制执行基于数据的业务逻辑的好地方。

技术答案很好,但你仍然“做错了”,除非你陷入多数据库平台环境,但在这种情况下,你可能做错了,除非你正在写一个数据层到为您处理数据库差异。

我认为我还应该补充一点,无论您使用的是存储过程还是多个语句,都应该使用限定名称dbo.tablename而不是tablename来引用表等。这可以通过避免在proc中进行不必要的安全检查来优化性能,但是在使用客户端生成的动态sql时,因为不使用dbo,这对性能至关重要。防止sql server重用已编译的sql并在经常调用时很快填满已编译的sql缓存。