因为SqlCommand实现了IDisposable,所以我通常会按照以下方式处理ADO查询。
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
// Execute command, etc. here
}但是,如果我需要在一个连接期间执行多个命令,怎么办?对于每个命令,我真的需要一个新的using块吗?
我从微软找到的示例不使用using块进行SqlCommand(甚至调用Dispose())。处理SqlCommand的最佳实践是什么?
发布于 2018-03-13 15:27:57
当然,最好的做法是处理它们。
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(query1, connection))
{
// Execute command, etc. here
}
using (SqlCommand command2 = new SqlCommand(query2, connection))
{
// Execute command, etc. here
}
using (SqlCommand command3 = new SqlCommand(query3, connection))
{
// Execute command, etc. here
}
}MSDN可能没有显示它,因为它是不需要在SqlCommand的情况下。但在我看来,微软没有在每个实现IDdisosable的对象上使用这种模式是不好的,因为人们还没有习惯它。
发布于 2018-03-13 15:27:03
using语句确保在调用对象上的方法时发生异常,也会调用Dispose。您可以通过将对象放在try块中,然后在一个Dispose块中调用finally来实现相同的结果。
在本例中,对每个命令块使用using:
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd1= new SqlCommand(query1, connection))
{
}
using (SqlCommand cmd2= new SqlCommand(query2, connection))
{
}
}发布于 2018-03-13 15:58:28
不你不知道。有两种方法可以将多个命令捆绑在一个连接和命令中。
第一种方法是重用现有的CMD对象,但根据需要更改CommandText和其他CMD.properties。
using (SqlConnection con = new SqlConnection(connectionString)) {
con.Open();
using (SqlCommand cmd = new SqlCommand(query1, con)) {
// cmd.CommandType = CommandType.xxxxx
// add any parameters
// Execute()
cmd.CommandText = query2;
// reset CommandType if needed
// adjust parameters if needed
// Execute()
cmd.CommandText = query 3;
// reset CommandType if needed
// adjust parameters if needed
// Execute()
}
con.Close();
}第二个方法是在数据库服务器上创建一个存储过程,并在一个CMD对象中调用它。
-- Database
CREATE PROCEDURE schema.sproc_CommandBatch (
-- any variables here
) AS
BEGIN
-- query 1
-- query 2
-- query 3
END
GO
// C#
using (SqlConnection con = new SqlConnection(connectionString)) {
con.Open();
using (SqlCommand cmd = new SqlCommand("schema.sproc_CommandBatch", con)) {
// cmd.CommandType = CommandType.StoredProcedure
// add any parameters
// Execute()
}
con.Close();
}https://stackoverflow.com/questions/49259804
复制相似问题