How to run multiple SQL commands in a single SQL connection?

前端 未结 9 965
野的像风
野的像风 2020-11-27 15:03

I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection. Here is the code I have written:

SqlConnection con = new SqlConn         


        
相关标签:
9条回答
  • 2020-11-27 15:58

    No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:

    using (SqlConnection conn = new SqlConnection(connString))
        {
            using (SqlCommand comm = new SqlCommand())
            {
                    comm.Connection = conn;
                    comm.CommandText = @"update table ... where myparam=@myparam1 ; " +
                                        "update table ... where myparam=@myparam2 ";
                    comm.Parameters.AddWithValue("@myparam1", myparam1);
                    comm.Parameters.AddWithValue("@myparam2", myparam2);
                    conn.Open();
                    comm.ExecuteNonQuery();
    
            }
        }
    
    0 讨论(0)
  • 2020-11-27 16:00

    I have not tested , but what the main idea is: put semicolon on each query.

    SqlConnection connection = new SqlConnection();
    SqlCommand command = new SqlCommand();
    connection.ConnectionString = connectionString; // put your connection string
    command.CommandText = @"
         update table
         set somecol = somevalue;
         insert into someTable values(1,'test');";
    command.CommandType = CommandType.Text;
    command.Connection = connection;
    
    try
    {
        connection.Open();
    }
    finally
    {
        command.Dispose();
        connection.Dispose();
    }
    

    Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too

    0 讨论(0)
  • 2020-11-27 16:03

    Just enable this property in your connection string:

    sqb.MultipleActiveResultSets = true;

    This property allows one open connection for multiple datareaders.

    0 讨论(0)
提交回复
热议问题