我需要在一个函数中运行多个查询,是否必须为每个查询创建一个新的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();
}
}发布于 2011-05-04 09:49:40
使用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发布于 2014-09-10 05:14:18
你走哪条路并不重要。
SqlConnections由操作系统池化。实际上,您可以连续数千次打开和关闭连接,而不会招致任何性能或其他损失。
它的工作原理是:
操作系统连接池(var c = new SqlConnection(...))
c.Dispose())这就是为什么当您第一次连接到数据库时,可能需要一秒钟才能启动,然后才能处理命令。但是,如果您将其关闭并重新打开,则连接将立即可用。更多信息在这里:http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx
现在,至于您的代码,一般来说,每次进行SqlCommand调用都会打开1个SqlConnection;但是,在SqlConnection using子句下的同一块中进行多个SqlCommand调用是完全可以接受的。
请记住,您不希望让SqlConnection对象在代码中停留的时间超过绝对必要的时间。这会导致很多潜在的问题,特别是当你在做web开发的时候。这意味着对于您的代码来说,快速连续地打开和关闭100个SqlConnection对象要比保留该对象并通过各种方法传递它要好得多。
发布于 2011-05-04 09:51:39
仅打开一个SQLConnection
使用带有的keyworkd ,因为它将自动处理连接。
如果为每一个都打开连接,则可能会出现性能问题。
示例:
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code shows how you can use an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}再举一个例子:
public DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("your connection here")
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "your stored procedure here";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return dt;
}https://stackoverflow.com/questions/5877584
复制相似问题