gpt4 book ai didi

c# - 多个 SQL 查询 asp.net c#

转载 作者:太空狗 更新时间:2023-10-29 20:01:55 28 4
gpt4 key购买 nike

我需要在一个函数内运行多个查询,是否必须为每个查询创建一个新的 SqlConnection?或者只有一个连接但不同的 SqlCommands 也能工作?

谢谢,

编辑:这行得通吗?

       using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();

using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.ExecuteNonQuery();
}

using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.ExecuteNonQuery();
}

using (SqlCommand cmd = new SqlCommand(query3, conn))
{
cmd.ExecuteNonQuery();
}

}

最佳答案

使用 MDSN Documentation作为基础:

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();

string sql1 = "SELECT ID,FirstName,LastName FROM VP_PERSON";
string sql2 = "SELECT Address,City,State,Code FROM VP_ADDRESS";

using (SqlCommand command = new SqlCommand(sql1,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}

} // command is disposed.

using (SqlCommand command = new SqlCommand(sql2,connection))
{

//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}

} // command is disposed.

// If you don't using using on your SqlCommands you need to dispose of them
// by calling command.Dispose(); on the command after you're done.

} // the SqlConnection will be disposed

关于c# - 多个 SQL 查询 asp.net c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877584/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com