我想对using
和SqlConnection
对象使用SqlCommand
来处理它们。在这种情况下如何使用?
例如:
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();
}
最佳答案
您可以像这样嵌套它们:
using (var _sqlConnection = new SqlConnection(...))
{
using (var sqlCmd = new SqlCommand(...))
{
//code
}
}