using System;
using System.Data;
using System.Xml;
using System.Data.Common;
using System.Collections;
//1 .优化掉了没用的函数
//2 .扩展事务
//3 .string commandText, params DbParameter[] commandParameters 好调试
//4 .全部完成 一开始打算使用List代替数组感觉没必要。
//List 类型安全问题与装箱拆箱的性能问题 EF为什么没用使用List检索速度没有数组快。所以就更别提再封装了。这样挺好的。
//根据Expression表达式生成SQL-Where部分的语句
namespace Core.Data
{
/// <summary>
/// The Database class is intended to encapsulate high performance, scalable best practices for
/// common uses of SqlClient
/// </summary>
public sealed class Database
{
private static DbProviderFactory dbFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
private static string connectionString = "Data Source=.;Initial Catalog=School;Persist Security Info=True;User ID=sa;password=123456;Pooling=True;Min Pool Size=10;Max Pool Size=200";
private static DbConnection CreateConnection()
{
DbConnection connection = dbFactory.CreateConnection();
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
public static DbTransaction BeginTransaction(IsolationLevel Iso)
{
return (CreateConnection()).BeginTransaction(Iso);
}
public static DbTransaction BeginTransaction()
{
return (CreateConnection()).BeginTransaction();
}
public static void Commit(DbTransaction Transaction)
{
DbConnection con = (DbConnection)Transaction.Connection;
Transaction.Commit();
con.Close();
}
public static void Rollback(DbTransaction Transaction)
{
DbConnection con = (DbConnection)Transaction.Connection;
Transaction.Rollback();
con.Close();
}
/// <summary>
/// 得到变量
/// </summary>
/// <param name="ParameterName"></param>
/// <param name="Value"></param>
/// <returns></returns>
public static DbParameter CreateParameter(string ParameterName, object Value)
{
return dbFactory.CreateParameter();
}
/// <summary>
/// 得到变量
/// </summary>
/// <param name="ParameterName"></param>
/// <param name="dbtype"></param>
/// <param name="size"></param>
/// <returns></returns>
public static DbParameter CreateParameter(string ParameterName, System.Data.SqlDbType dbtype, int size)
{
return dbFactory.CreateParameter();
}
#region private utility methods & constructors
// Since this class provides only static methods, make the default constructor private to prevent
// instances from being created with "new Database()"
private Database() { }
/// <summary>
/// This method is used to attach array of DbParameters to a DbCommand.
///
/// This method will assign a value of DbNull to any parameter with a direction of
/// InputOutput and a value of null.
///
/// This behavior will prevent default values from being used, but
/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
/// where the user provided no input value.
/// </summary>
/// <param name="command">The command to which the parameters will be added</param>
/// <param name="commandParameters">An array of DbParameters to be added to command</param>
private static void AttachParameters(DbCommand command, DbParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("command");
if (commandParameters != null)
{
foreach (DbParameter p in commandParameters)
{
if (p != null)
{
// Check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput ||
p.Direction == ParameterDirection.Input) &&
(p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
}
/// <summary>
/// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
/// to the provided command
/// </summary>
/// <param name="command">The DbCommand to be prepared</param>
/// <param name="connection">A valid DbConnection, on which to execute this command</param>
/// <param name="transaction">A valid DbTransaction, or 'null'</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of DbParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
private static void PrepareCommand(DbCommand command, DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, DbParameter[] commandParameters, out bool mustCloseConnection)
{
if (command == null) throw new ArgumentNullException("command");
if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
// If the provided connection is not open, we will open it
if (connection.State != ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
}
// Associate the connection with the command
command.Connection = connection;
// Set the command text (stored procedure name or SQL statement)
command.CommandText = commandText;
// If we were provided a transaction, assign it
if (transaction != null)
{
if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
command.Transaction = transaction;
}
// Set the command type
command.CommandType = commandType;
// Attach the command parameters if they are provided
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
}
#endregion private utility methods & constructors
#region ExecuteNonQuery
/// <summary>
/// Execute a DbCommand (that returns no resultset and takes no parameters) against the database specified in
/// the connection string
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteNonQuery(CommandType.Text, commandText);
}
/// <summary>
/// Execute a DbCommand (that returns no resultset) against the specified DbConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string commandText, params DbParameter[] commandParameters)
{
using (DbConnection connection = CreateConnection())
{
// Create a command and prepare it for execution
DbCommand cmd = connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, CommandType.Text, commandText, commandParameters, out mustCloseConnection);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}
/// <summary>
/// Execute a DbCommand (that returns no resultset and takes no parameters) against the provided DbConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteNonQuery(commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns no resultset) against the specified DbConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid DbConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
using (DbConnection connection = CreateConnection())
{
// Create a command and prepare it for execution
DbCommand cmd = connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}
/// <summary>
/// Execute a DbCommand (that returns no resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(DbTransaction transaction, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteNonQuery(transaction, CommandType.Text, commandText);
}
/// <summary>
/// Execute a DbCommand (that returns no resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(DbTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteNonQuery(transaction, commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns no resultset) against the specified DbTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(DbTransaction transaction, CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
DbCommand cmd = transaction.Connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
#endregion ExecuteNonQuery
#region ExecuteDataset
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteDataset(commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string commandText, params DbParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
// Create & open a DbConnection, and dispose of it after we are done
// Call the overload that takes a connection in place of the connection string
return ExecuteDataset(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(CommandType commandType, string commandText)
{
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
// Create & open a DbConnection, and dispose of it after we are done
// Call the overload that takes a connection in place of the connection string
return ExecuteDataset(commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset) against the specified DbConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
using (DbConnection connection = CreateConnection())
{
// Create a command and prepare it for execution
DbCommand cmd = connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
// Create the DataAdapter & DataSet
using (DbDataAdapter dbDataAdapter = dbFactory.CreateDataAdapter())
{
DataSet ds = new DataSet();
dbDataAdapter.SelectCommand = cmd;
// Fill the DataSet using default values for DataTable names, etc
dbDataAdapter.Fill(ds);
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
// Return the dataset
return ds;
}
}
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(DbTransaction transaction, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteDataset(transaction, CommandType.Text, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(DbTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteDataset(transaction, commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset) against the specified DbTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(DbTransaction transaction, CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
DbCommand cmd = transaction.Connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
// Create the DataAdapter & DataSet
using (DbDataAdapter dbDataAdapter = dbFactory.CreateDataAdapter())
{
DataSet ds = new DataSet();
dbDataAdapter.SelectCommand = cmd;
// Fill the DataSet using default values for DataTable names, etc
dbDataAdapter.Fill(ds);
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
// Return the dataset
return ds;
}
}
#endregion ExecuteDataset
#region ExecuteReader
/// <summary>
/// This enum is used to indicate whether the connection was provided by the caller, or created by Database, so that
/// we can set the appropriate CommandBehavior when calling ExecuteReader()
/// </summary>
private enum DbConnectionOwnership
{
/// <summary>Connection is owned and managed by Database</summary>
Internal,
/// <summary>Connection is owned and managed by the caller</summary>
External
}
/// <summary>
/// Create and prepare a DbCommand, and call ExecuteReader with the appropriate CommandBehavior.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="connection">A valid DbConnection, on which to execute this command</param>
/// <param name="transaction">A valid DbTransaction, or 'null'</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of DbParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by Database</param>
/// <returns>DbDataReader containing the results of the command</returns>
private static DbDataReader ExecuteReader(DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, DbParameter[] commandParameters, DbConnectionOwnership connectionOwnership)
{
if (connection == null) throw new ArgumentNullException("connection");
bool mustCloseConnection = false;
// Create a command and prepare it for execution
DbCommand cmd = connection.CreateCommand();
try
{
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
// Create a reader
DbDataReader dataReader;
// Call ExecuteReader with the appropriate CommandBehavior
if (connectionOwnership == DbConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
// Detach the DbParameters 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 (DbParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
canClear = false;
}
if (canClear)
{
cmd.Parameters.Clear();
}
return dataReader;
}
catch
{
if (mustCloseConnection)
connection.Close();
throw;
}
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteReader(CommandType.Text, commandText);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(string commandText, params DbParameter[] commandParameters)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteReader(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteReader(commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a DbConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
DbConnection connection = null;
try
{
connection = CreateConnection();
// Call the private overload that takes an internally owned connection in place of the connection string
return ExecuteReader(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch
{
// If we fail to return the SqlDatReader, we need to close the connection ourselves
if (connection != null) connection.Close();
throw;
}
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(DbTransaction transaction, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteReader(transaction, CommandType.Text, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(DbTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteReader(transaction, commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a resultset) against the specified DbTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DbDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A DbDataReader containing the resultset generated by the command</returns>
public static DbDataReader ExecuteReader(DbTransaction transaction, CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Pass through to private overload, indicating that the connection is owned by the caller
return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
#endregion ExecuteReader
#region ExecuteScalar
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connectionString">A valid connection string for a DbConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteScalar(CommandType.Text, commandText);
}
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset and takes no parameters) against the provided DbConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string commandText, params DbParameter[] commandParameters)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteScalar(CommandType.Text, commandText, commandParameters);
}
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset and takes no parameters) against the provided DbConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteScalar(commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset) against the specified DbConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid DbConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
using (DbConnection connection = CreateConnection())
{
// Create a command and prepare it for execution
DbCommand cmd = connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
// Execute the command & return the results
object retval = cmd.ExecuteScalar();
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(DbTransaction transaction, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteScalar(transaction, CommandType.Text, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset and takes no parameters) against the provided DbTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(DbTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of DbParameters
return ExecuteScalar(transaction, commandType, commandText, (DbParameter[])null);
}
/// <summary>
/// Execute a DbCommand (that returns a 1x1 resultset) against the specified DbTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new DbParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid DbTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(DbTransaction transaction, CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
DbCommand cmd = transaction.Connection.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
// Execute the command & return the results
object retval = cmd.ExecuteScalar();
// Detach the DbParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
#endregion ExecuteScalar
}
}