/// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
/// we can set the appropriate CommandBehavior when calling ExecuteReader()
///
private enum SqlConnectionOwnership
{
/// Connection is owned and managed by SqlHelper
Internal,
/// Connection is owned and managed by the caller
External
}
///
/// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
///
///
/// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
///
/// If the caller provided the connection, we want to leave it to them to manage.
///
/// A valid SqlConnection, on which to execute this command
/// A valid SqlTransaction, or 'null'
/// The CommandType (stored procedure, text, etc.)
/// The stored procedure name or T-SQL command
/// An array of SqlParameters to be associated with the command or 'null' if no parameters are required
/// Indicates whether the connection parameter was provided by the caller, or created by SqlHelper
/// SqlDataReader containing the results of the command
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
{
if( connection == null ) throw new ArgumentNullException( "connection" );
bool mustCloseConnection = false;
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
// Create a reader
SqlDataReader dataReader;
// Call ExecuteReader with the appropriate CommandBehavior
if (connectionOwnership == SqlConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
// Detach the SqlParameters from the command object, so they can be used again.
// HACK: There is a problem here, the output parameter values are fletched
// when the reader is closed, so if the parameters are detached from the command
// then the SqlReader can磘 set its values.
// When this happen, the parameters can磘 be used again in other command.
bool canClear = true;
foreach(SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
canClear = false;
}
if (canClear)
{
cmd.Parameters.Clear();
}
return dataReader;
}
catch
{
if( mustCloseConnection )
connection.Close();
throw;
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8781179/viewspace-924787/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/8781179/viewspace-924787/
本文介绍了一个用于管理SQL连接并执行SQL命令的方法。通过定义枚举`SqlConnectionOwnership`来区分连接的所有权,确保了在使用`SqlHelper`执行SQL命令时能够正确设置`CommandBehavior`。此外,详细介绍了如何创建和准备`SqlCommand`对象,并调用`ExecuteReader()`方法执行查询。
113

被折叠的 条评论
为什么被折叠?



