1

我想使用usingforSqlConnectionSqlCommandobjects 来处理这些。在这种情况下如何使用?

例如:

using (sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL")))
{
}

但这里我使用的是基于 if 条件的连接。

SqlConnection _sqlConnection;
SqlCommand sqlCmd;
DBPersister per = (DBPersister)invoice;
if (per == null)
{
    _sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"));
    sqlCmd = new SqlCommand("usp_UpdateDocumentStatusInImages", _sqlConnection);
}
else
{
    _sqlConnection = per.GetConnection();
    sqlCmd = per.GenerateCommand("usp_UpdateDocumentStatusInImages", _sqlConnection, per);
}

sqlCmd.CommandType = CommandType.StoredProcedure;
//mycode

try
{
    if (_sqlConnection.State == ConnectionState.Closed)
        _sqlConnection.Open();
    sqlCmd.ExecuteNonQuery();
}
catch
{
    throw;
}
finally
{
    if (per == null)
        invoice._sqlConnection.Close();
}
4

2 回答 2

4

您可以嵌套它们,如下所示:

using (var _sqlConnection = new SqlConnection(...))
{
    using (var sqlCmd = new SqlCommand(...))
    {
        //code
    }
}
于 2013-01-08T07:47:33.437 回答
1

使用条件运算符来确定分配给每个变量的内容:

using(SqlConnection _sqlConnection = per==null?
      new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"))
      : per.GetConnection())
using(SqlCommand sqlCmd = per==null?
      new SqlCommand("usp_UpdateDocumentStatusInImages", _sqlConnection);
      : per.GenerateCommand("usp_UpdateDocumentStatusInImages", 
       _sqlConnection, per))
{
  //Code here using command and connection
}

虽然我必须说,per.GenerateCommand(..., per)它看起来像一个奇怪的函数(它是一个实例方法,也必须传递同一个类的实例 - 它必须始终是同一个实例吗?)

于 2013-01-08T07:45:24.740 回答