如何在单个SQL连接中运行多个SQL命令?

时间:2012-12-03 04:51:57

标签: c# sql-server ado.net sqlconnection sqlcommand

我正在创建一个项目,我需要在单个sql连接中运行2-3个sql命令。 这是我写的代码:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select *  from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
    con.Close();
    con.Open();
    SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname@gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
    cmd1.ExecuteNonQuery();
    label.Visible = true;
    label.Text = "Date read and inserted";
}
else
{
    con.Close();
    con.Open();
    SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
    cmd2.ExecuteNonQuery();
    con.Close();
    con.Open();
    SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
    cmd3.ExecuteNonQuery();
    label.Visible = true;
    label.Text = "tabel created";
    con.Close();
}

我试图删除错误,我得到了连接不会发生其他情况。请查看代码并建议是否有任何错误或任何其他解决方案。

9 个答案:

答案 0 :(得分:43)

只需更改SqlCommand.CommandText,而不是每次都创建新的SqlCommand。无需关闭并重新打开连接。

// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();

// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();

答案 1 :(得分:27)

以下内容应该有效。保持单个连接始终打开,只需创建新命令并执行它们。

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (SqlCommand command1 = new SqlCommand(commandText1, connection))
    {
    }
    using (SqlCommand command2 = new SqlCommand(commandText2, connection))
    {
    }
    // etc
}

答案 2 :(得分:16)

只需在连接字符串中启用此属性:

sqb.MultipleActiveResultSets = true;

此属性为多个数据加载器提供了一个开放式连接

答案 3 :(得分:10)

我没有测试过,但主要的想法是:在每个查询上加上分号。

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

<强>更新 你可以关注 Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property?也是

答案 4 :(得分:8)

顺便说一句,这可能会通过SQL注入进行攻击。在阅读并相应调整您的查询时,这是值得的。

甚至可以考虑为此创建存储过程并使用类似sp_executesql的东西,当动态sql是一个要求时(即未知的表名等),它可以提供一些保护。有关详细信息,请查看this link

答案 5 :(得分:2)

没有人提到这一点,但是您也可以使用;分隔命令。同一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();

        }
    }

答案 6 :(得分:1)

如果有人感兴趣,则为多个非查询示例。

using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
  DbConnection.Open();
  using (OdbcCommand DbCommand = DbConnection.CreateCommand())
  {
    DbCommand.CommandText = "INSERT...";
    DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name";
    DbCommand.ExecuteNonQuery();

    DbCommand.Parameters.Clear();
    DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name2";
    DbCommand.ExecuteNonQuery();
  }
}

答案 7 :(得分:0)

在这里你可以找到Postgre示例,这段代码在单个SQL连接中运行多个sql命令(更新2列)

public static class SQLTest
    {
        public static void NpgsqlCommand()
        {
            using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
            {
                NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
                NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
                command1.Connection.Open();
                command1.ExecuteNonQuery();
                command2.ExecuteNonQuery();
                command2.Connection.Close();
            }
        }
    }

答案 8 :(得分:0)

const getRef = firebase.firestore().collection('customers').doc('andreas');

const response = await getRef.get();  

console.log(response.data()); // answer { bookings: [ '123booking', '456booking' ] }


// then i'm trying to delete the element with value 123booking: 

let deleteRef = firebase.firestore().collection('customers').doc('andreas');

const removeRes = await deleteRef.update({
    bookings: admin.firestore.FieldValue.arrayRemove('123booking')
});