处理SqlConnection,SqlTransaction,SqlCommand,SqlDataAdapter对象的最佳实践

时间:2017-11-15 08:00:02

标签: .net sql-server ado.net sqlconnection sqltransaction

是否所有sqlCommand,sqlTransaction和sqlDataAdapter对象自动在退出“using”块(其中放置了sqlConnection)或要处置的所有这些对象处于分离< / strong>嵌套“使用”块,否则当sqlConnection对象处置时这些对象不会被处理?什么是最佳做法?

public static void ExecuteDataset(string connectionString, string storedProcedure, SqlParameter[] sqlParameters = null)
{
    SqlTransaction sqlTransaction = null;

    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
    {
        try
        {
            sqlConnection.Open();

            SqlCommand sqlCommand = new SqlCommand(commandText, connection);
            command.Parameters.Add("@ID", SqlDbType.Int);

            sqlCommand.Connection = sqlConnection;
            SqlTransaction = sqlConnection.BeginTransaction();
            sqlCommand.Transaction = sqlTransaction;
            .....................................................
            .....................................................    

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();

                ................................
                ................................


            sqlTransaction.Commit();
        }
        catch (Exception)
        {
            sqlTransaction.Rollback();
        }
    }        
}

1 个答案:

答案 0 :(得分:3)

如果对象实现IDisposable,则使用usingSqlConnectionSqlCommand或任何其他对象的基础实现细节无关紧要。

对于您的场景,最佳做法是

using(var conn = new SqlConnection(...)) {
  ...
  using(var cmd = conn.CreateCommand(...)) {
    ...
  }
  ...
}