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

问题描述 投票:33回答:6

我正在创建一个项目,我需要在单个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 ('[email protected]','" + 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();
}

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

c# sql-server ado.net sqlconnection sqlcommand
6个回答
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();

27
投票

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

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

15
投票

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

sqb.MultipleActiveResultSets = true;

此属性允许多个数据读取器的一个开放连接


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?


8
投票

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

也许看看甚至为此创建存储过程并使用像sp_executesql这样的东西,当动态sql是一个要求时(即未知的表名等)可以提供一些保护。有关更多信息,请查看this link


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();
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.