微软官方SqlHelper
来源:互联网 发布:windows线程优先级 编辑:程序博客网 时间:2024/06/03 21:23
从微软官方下载的SqlHelper
using System;
usingSystem.Collections;
usingSystem.Collections.Generic;
using System.Data;
usingSystem.Data.SqlClient;
using System.Linq;
using System.Text;
usingSystem.Threading.Tasks;
using System.Xml;
namespace DAL.Tool
{
internal sealed class SqlHelper
{
#region private utility methods &constructors
// Since this class provides onlystatic methods, make the default constructor private to prevent
// instances from being created with"new SqlHelper()"
private SqlHelper() { }
/// <summary>
/// This method is used to attach arrayof SqlParameters to a SqlCommand.
///
/// This method will assign a value ofDbNull to any parameter with a direction of
/// InputOutput and a value ofnull.
///
/// This behavior will prevent defaultvalues from being used, but
/// this will be the less common casethan an intended pure output parameter (derived as InputOutput)
/// where the user provided no inputvalue.
/// </summary>
/// <paramname="command">The command to which the parameters will beadded</param>
/// <paramname="commandParameters">An array of SqlParameters to be added tocommand</param>
private static voidAttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
if (command == null) throw newArgumentNullException("command");
if (commandParameters != null)
{
foreach (SqlParameter p incommandParameters)
{
if (p != null)
{
// Check for derivedoutput 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 assigns dataRow columnvalues to an array of SqlParameters
/// </summary>
/// <paramname="commandParameters">Array of SqlParameters to be assignedvalues</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values</param>
private static voidAssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
{
if ((commandParameters == null) ||(dataRow == null))
{
// Do nothing if we get no data
return;
}
int i = 0;
// Set the parameters values
foreach (SqlParametercommandParameter in commandParameters)
{
// Check the parameter name
if(commandParameter.ParameterName == null ||
commandParameter.ParameterName.Length <= 1)
throw new Exception(
string.Format(
"Pleaseprovide a valid parameter name on the parameter #{0}, the ParameterNameproperty has the following value: '{1}'.",
i,commandParameter.ParameterName));
if(dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) !=-1)
commandParameter.Value =dataRow[commandParameter.ParameterName.Substring(1)];
i++;
}
}
/// <summary>
/// This method assigns an array ofvalues to an array of SqlParameters
/// </summary>
/// <paramname="commandParameters">Array of SqlParameters to be assignedvalues</param>
/// <paramname="parameterValues">Array of objects holding the values to beassigned</param>
private static voidAssignParameterValues(SqlParameter[] commandParameters, object[]parameterValues)
{
if ((commandParameters == null) ||(parameterValues == null))
{
// Do nothing if we get no data
return;
}
// We must have the same number ofvalues as we pave parameters to put them in
if (commandParameters.Length !=parameterValues.Length)
{
throw newArgumentException("Parameter count does not match Parameter Valuecount.");
}
// Iterate through theSqlParameters, assigning the values from the corresponding position in the
// value array
for (int i = 0, j =commandParameters.Length; i < j; i++)
{
// If the current array valuederives from IDbDataParameter, then assign its Value property
if (parameterValues[i] isIDbDataParameter)
{
IDbDataParameterparamInstance = (IDbDataParameter)parameterValues[i];
if (paramInstance.Value ==null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = paramInstance.Value;
}
}
else if (parameterValues[i] ==null)
{
commandParameters[i].Value= DBNull.Value;
}
else
{
commandParameters[i].Value= parameterValues[i];
}
}
}
/// <summary>
/// This method opens (if necessary)and assigns a connection, transaction, command type and parameters
/// to the provided command
/// </summary>
/// <paramname="command">The SqlCommand to be prepared</param>
/// <paramname="connection">A valid SqlConnection, on which to execute thiscommand</param>
/// <paramname="transaction">A valid SqlTransaction, or 'null'</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParameters to beassociated with the command or 'null' if no parameters arerequired</param>
/// <paramname="mustCloseConnection"><c>true</c> if theconnection was opened by the method, otherwose is false.</param>
private static voidPrepareCommand(SqlCommand command, SqlConnection connection, SqlTransactiontransaction, CommandType commandType, string commandText, SqlParameter[]commandParameters, out bool mustCloseConnection)
{
if (command == null) throw newArgumentNullException("command");
if (commandText == null ||commandText.Length == 0) throw newArgumentNullException("commandText");
// If the provided connection isnot open, we will open it
if (connection.State !=ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
}
// Associate the connection withthe command
command.Connection = connection;
// Set the command text (storedprocedure name or SQL statement)
command.CommandText = commandText;
// If we were provided atransaction, assign it
if (transaction != null)
{
if (transaction.Connection ==null) throw new ArgumentException("The transaction was rollbacked orcommited, please provide an open transaction.", "transaction");
command.Transaction =transaction;
}
// Set the command type
command.CommandType = commandType;
// Attach the command parameters ifthey are provided
if (commandParameters != null)
{
AttachParameters(command,commandParameters);
}
return;
}
#endregion private utility methods& constructors
#region ExecuteNonQuery
/// <summary>
/// Execute a SqlCommand (that returnsno 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>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(string connectionString, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
returnExecuteNonQuery(connectionString, commandType, commandText,(SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsno resultset) against the database specified in the connection string
/// using the provided parameters
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure,"PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(string connectionString, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
// Create & open aSqlConnection, and dispose of it after we are done
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takesa connection in place of the connection string
returnExecuteNonQuery(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns no resultset) against the database specified in
/// the connection string using theprovided parameter values. This methodwill query the database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int result = ExecuteNonQuery(connString, "PublishOrders", 24,36);
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored prcedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(string connectionString, string spName, params object[]parameterValues)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsno resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure,"PublishOrders");
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(SqlConnection connection, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteNonQuery(connection,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsno resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure,"PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(SqlConnection connection, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw newArgumentNullException("connection");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection,(SqlTransaction)null, commandType, commandText, commandParameters, outmustCloseConnection);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the SqlParameters fromthe command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns no resultset) against the specified SqlConnection
/// using the provided parametervalues. This method will query thedatabase to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(SqlConnection connection, string spName, params object[]parameterValues)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteNonQuery(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsno resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure,"PublishOrders");
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(SqlTransaction transaction, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteNonQuery(transaction,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsno resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(SqlTransaction transaction, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd,transaction.Connection, transaction, commandType, commandText,commandParameters, out mustCloseConnection);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the SqlParameters fromthe command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns no resultset) against the specified
/// SqlTransaction using the providedparameter values. This method will querythe database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24,36);
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQuery(SqlTransaction transaction, string spName, params object[]parameterValues)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteNonQuery(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteNonQuery
#region ExecuteDataset
/// <summary>
/// Execute a SqlCommand (that returnsa 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>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(string connectionString, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
returnExecuteDataset(connectionString, commandType, commandText,(SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa 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 SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(string connectionString, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
// Create & open aSqlConnection, and dispose of it after we are done
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takesa connection in place of the connection string
returnExecuteDataset(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the database specified in
/// the connection string using theprovided parameter values. This methodwill query the database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(string connectionString, string spName, params object[]parameterValues)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteDataset(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure,"GetOrders");
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(SqlConnection connection, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteDataset(connection,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(SqlConnection connection, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw newArgumentNullException("connection");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection,(SqlTransaction)null, commandType, commandText, commandParameters, outmustCloseConnection);
// Create the DataAdapter &DataSet
using (SqlDataAdapter da = newSqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
// Fill the DataSet usingdefault values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParametersfrom the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
// Return the dataset
return ds;
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parametervalues. This method will query thedatabase to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(SqlConnection connection, string spName, params object[]parameterValues)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteDataset(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure,"GetOrders");
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(SqlTransaction transaction, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteDataset(transaction,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(SqlTransaction transaction, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd,transaction.Connection, transaction, commandType, commandText,commandParameters, out mustCloseConnection);
// Create the DataAdapter &DataSet
using (SqlDataAdapter da = newSqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
// Fill the DataSet usingdefault values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParametersfrom the command object, so they can be used again
cmd.Parameters.Clear();
// Return the dataset
return ds;
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the providedparameter values. This method will querythe database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDataset(SqlTransaction transaction, string spName, params object[]parameterValues)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteDataset(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteDataset
#region ExecuteReader
/// <summary>
/// This enum is used to indicatewhether the connection was provided by the caller, or created by SqlHelper, sothat
/// we can set the appropriateCommandBehavior when calling ExecuteReader()
/// </summary>
private enum SqlConnectionOwnership
{
/// <summary>Connection isowned and managed by SqlHelper</summary>
Internal,
/// <summary>Connection isowned and managed by the caller</summary>
External
}
/// <summary>
/// Create and prepare a SqlCommand,and call ExecuteReader with the appropriate CommandBehavior.
/// </summary>
/// <remarks>
/// If we created and opened theconnection, we want the connection to be closed when the DataReader is closed.
///
/// If the caller provided theconnection, we want to leave it to them to manage.
/// </remarks>
/// <paramname="connection">A valid SqlConnection, on which to execute thiscommand</param>
/// <paramname="transaction">A valid SqlTransaction, or 'null'</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParameters to beassociated with the command or 'null' if no parameters arerequired</param>
/// <paramname="connectionOwnership">Indicates whether the connectionparameter was provided by the caller, or created by SqlHelper</param>
/// <returns>SqlDataReadercontaining the results of the command</returns>
private static SqlDataReaderExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandTypecommandType, string commandText, SqlParameter[] commandParameters,SqlConnectionOwnership connectionOwnership)
{
if (connection == null) throw newArgumentNullException("connection");
bool mustCloseConnection = false;
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection,transaction, commandType, commandText, commandParameters, outmustCloseConnection);
// Create a reader
SqlDataReader dataReader;
// Call ExecuteReader with theappropriate CommandBehavior
if (connectionOwnership ==SqlConnectionOwnership.External)
{
dataReader =cmd.ExecuteReader();
}
else
{
dataReader =cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
// Detach the SqlParametersfrom the command object, so they can be used again.
// HACK: There is a problemhere, the output parameter values are fletched
// when the reader is closed,so if the parameters are detached from the command
// then theSqlReader can磘 set its values.
// When thishappen, the parameters can磘 be used again in other command.
bool canClear = true;
foreach (SqlParametercommandParameter 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 SqlCommand (that returnsa resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString,CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(string connectionString, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
returnExecuteReader(connectionString, commandType, commandText,(SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString,CommandType.StoredProcedure, "GetOrders", newSqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(string connectionString, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
SqlConnection connection = null;
try
{
connection = newSqlConnection(connectionString);
connection.Open();
// Call the private overloadthat takes an internally owned connection in place of the connection string
returnExecuteReader(connection, null, commandType, commandText, commandParameters,SqlConnectionOwnership.Internal);
}
catch
{
// If we fail to return theSqlDatReader, we need to close the connection ourselves
if (connection != null)connection.Close();
throw;
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the database specified in
/// the connection string using theprovided parameter values. This methodwill query the database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24,36);
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(string connectionString, string spName, params object[]parameterValues)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
AssignParameterValues(commandParameters, parameterValues);
returnExecuteReader(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure,"GetOrders");
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(SqlConnection connection, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteReader(connection,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(SqlConnection connection, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
// Pass through the call to theprivate overload using a null transaction value and an externally ownedconnection
return ExecuteReader(connection,(SqlTransaction)null, commandType, commandText, commandParameters,SqlConnectionOwnership.External);
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parametervalues. This method will query thedatabase to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(SqlConnection connection, string spName, params object[]parameterValues)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
AssignParameterValues(commandParameters, parameterValues);
returnExecuteReader(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteReader(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure,"GetOrders");
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(SqlTransaction transaction, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteReader(transaction,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(SqlTransaction transaction, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
// Pass through to privateoverload, indicating that the connection is owned by the caller
returnExecuteReader(transaction.Connection, transaction, commandType, commandText,commandParameters, SqlConnectionOwnership.External);
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the providedparameter values. This method will querythe database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReader(SqlTransaction transaction, string spName, params object[]parameterValues)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
AssignParameterValues(commandParameters, parameterValues);
returnExecuteReader(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteReader
#region ExecuteScalar
/// <summary>
/// Execute a SqlCommand (that returnsa 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>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(string connectionString, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
returnExecuteScalar(connectionString, commandType, commandText,(SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa 1x1 resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString,CommandType.StoredProcedure, "GetOrderCount", newSqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(string connectionString, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
// Create & open aSqlConnection, and dispose of it after we are done
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takesa connection in place of the connection string
returnExecuteScalar(connection, commandType, commandText, commandParameters);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a 1x1 resultset) against the database specified in
/// the connection string using theprovided parameter values. This methodwill query the database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString,"GetOrderCount", 24, 36);
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(string connectionString, string spName, params object[]parameterValues)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteScalar(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa 1x1 resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure,"GetOrderCount");
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(SqlConnection connection, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteScalar(connection,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa 1x1 resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure,"GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(SqlConnection connection, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw newArgumentNullException("connection");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection,(SqlTransaction)null, commandType, commandText, commandParameters, outmustCloseConnection);
// Execute the command & returnthe results
object retval =cmd.ExecuteScalar();
// Detach the SqlParameters fromthe command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the provided parametervalues. This method will query thedatabase to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24,36);
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(SqlConnection connection, string spName, params object[]parameterValues)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteScalar(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa 1x1 resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure,"GetOrderCount");
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(SqlTransaction transaction, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteScalar(transaction,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa 1x1 resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure,"GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(SqlTransaction transaction, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd,transaction.Connection, transaction, commandType, commandText,commandParameters, out mustCloseConnection);
// Execute the command & returnthe results
object retval =cmd.ExecuteScalar();
// Detach the SqlParameters fromthe command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a 1x1 resultset) against the specified
/// SqlTransaction using the providedparameter values. This method will querythe database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount",24, 36);
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalar(SqlTransaction transaction, string spName, params object[]parameterValues)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// PPull the parameters forthis stored procedure from the parameter cache (or discover them & populatethe cache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteScalar(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteScalar
#region ExecuteXmlReader
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure,"GetOrders");
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQL commandusing "FOR XML AUTO"</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReader(SqlConnection connection, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
return ExecuteXmlReader(connection,commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQL commandusing "FOR XML AUTO"</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReader(SqlConnection connection, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw newArgumentNullException("connection");
bool mustCloseConnection = false;
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection,(SqlTransaction)null, commandType, commandText, commandParameters, outmustCloseConnection);
// Create the DataAdapter &DataSet
XmlReader retval =cmd.ExecuteXmlReader();
// Detach the SqlParametersfrom the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
catch
{
if (mustCloseConnection)
connection.Close();
throw;
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parametervalues. This method will query thedatabase to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="spName">The name of the stored procedure using "FOR XMLAUTO"</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReader(SqlConnection connection, string spName, params object[]parameterValues)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteXmlReader(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure,"GetOrders");
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQL commandusing "FOR XML AUTO"</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReader(SqlTransaction transaction, CommandType commandType, stringcommandText)
{
// Pass through the call providingnull for the set of SqlParameters
returnExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure,"GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQL commandusing "FOR XML AUTO"</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReader(SqlTransaction transaction, CommandType commandType, stringcommandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
// Create a command and prepare itfor execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd,transaction.Connection, transaction, commandType, commandText,commandParameters, out mustCloseConnection);
// Create the DataAdapter &DataSet
XmlReader retval =cmd.ExecuteXmlReader();
// Detach the SqlParameters fromthe command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the providedparameter values. This method will querythe database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReader(SqlTransaction transaction, string spName, params object[]parameterValues)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
returnExecuteXmlReader(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
returnExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion ExecuteXmlReader
#region FillDataset
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(connString, CommandType.StoredProcedure,"GetOrders", ds, new string[] {"orders"});
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)</param>
internal static void FillDataset(stringconnectionString, CommandType commandType, string commandText, DataSet dataSet,string[] tableNames)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (dataSet == null) throw newArgumentNullException("dataSet");
// Create & open aSqlConnection, and dispose of it after we are done
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takesa connection in place of the connection string
FillDataset(connection,commandType, commandText, dataSet, tableNames);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(connString, CommandType.StoredProcedure,"GetOrders", ds, new string[] {"orders"}, newSqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
internal static void FillDataset(stringconnectionString, CommandType commandType,
string commandText, DataSetdataSet, string[] tableNames,
params SqlParameter[]commandParameters)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (dataSet == null) throw newArgumentNullException("dataSet");
// Create & open aSqlConnection, and dispose of it after we are done
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takesa connection in place of the connection string
FillDataset(connection,commandType, commandText, dataSet, tableNames, commandParameters);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the database specified in
/// the connection string using theprovided parameter values. This methodwill query the database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// FillDataset(connString, CommandType.StoredProcedure,"GetOrders", ds, new string[] {"orders"}, 24);
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
internal static void FillDataset(stringconnectionString, string spName,
DataSet dataSet, string[]tableNames,
params object[] parameterValues)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (dataSet == null) throw newArgumentNullException("dataSet");
// Create & open aSqlConnection, and dispose of it after we are done
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
// Call the overload that takesa connection in place of the connection string
FillDataset(connection, spName,dataSet, tableNames, parameterValues);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(conn, CommandType.StoredProcedure, "GetOrders",ds, new string[] {"orders"});
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
internal static voidFillDataset(SqlConnection connection, CommandType commandType,
string commandText, DataSetdataSet, string[] tableNames)
{
FillDataset(connection,commandType, commandText, dataSet, tableNames, null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(conn, CommandType.StoredProcedure, "GetOrders",ds, new string[] {"orders"}, new SqlParameter("@prodid",24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
internal static voidFillDataset(SqlConnection connection, CommandType commandType,
string commandText, DataSetdataSet, string[] tableNames,
params SqlParameter[]commandParameters)
{
FillDataset(connection, null,commandType, commandText, dataSet, tableNames, commandParameters);
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parametervalues. This method will query thedatabase to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// FillDataset(conn, "GetOrders", ds, new string[]{"orders"}, 24, 36);
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
internal static voidFillDataset(SqlConnection connection, string spName,
DataSet dataSet, string[]tableNames,
params object[] parameterValues)
{
if (connection == null) throw newArgumentNullException("connection");
if (dataSet == null) throw newArgumentNullException("dataSet");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
FillDataset(connection,CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
FillDataset(connection,CommandType.StoredProcedure, spName, dataSet, tableNames);
}
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(trans, CommandType.StoredProcedure, "GetOrders",ds, new string[] {"orders"});
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
internal static voidFillDataset(SqlTransaction transaction, CommandType commandType,
string commandText,
DataSet dataSet, string[]tableNames)
{
FillDataset(transaction,commandType, commandText, dataSet, tableNames, null);
}
/// <summary>
/// Execute a SqlCommand (that returnsa resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(trans, CommandType.StoredProcedure, "GetOrders",ds, new string[] {"orders"}, new SqlParameter("@prodid",24));
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
internal static voidFillDataset(SqlTransaction transaction, CommandType commandType,
string commandText, DataSetdataSet, string[] tableNames,
params SqlParameter[]commandParameters)
{
FillDataset(transaction.Connection,transaction, commandType, commandText, dataSet, tableNames, commandParameters);
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the providedparameter values. This method will querythe database to discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <remarks>
/// This method provides no access tooutput parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// FillDataset(trans, "GetOrders", ds, newstring[]{"orders"}, 24, 36);
/// </remarks>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
/// <paramname="parameterValues">An array of objects to be assigned as theinput values of the stored procedure</param>
internal static voidFillDataset(SqlTransaction transaction, string spName,
DataSet dataSet, string[]tableNames,
params object[] parameterValues)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (dataSet == null) throw newArgumentNullException("dataSet");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If we receive parameter values,we need to figure out where they go
if ((parameterValues != null)&& (parameterValues.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Assign the provided valuesto these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);
// Call the overload that takesan array of SqlParameters
FillDataset(transaction,CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
// Otherwise we can just callthe SP without params
FillDataset(transaction,CommandType.StoredProcedure, spName, dataSet, tableNames);
}
}
/// <summary>
/// Private helper method that executea SqlCommand (that returns a resultset) against the specified SqlTransactionand SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(conn, trans, CommandType.StoredProcedure,"GetOrders", ds, new string[] {"orders"}, newSqlParameter("@prodid", 24));
/// </remarks>
/// <paramname="connection">A valid SqlConnection</param>
/// <paramname="transaction">A valid SqlTransaction</param>
/// <paramname="commandType">The CommandType (stored procedure, text,etc.)</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="dataSet">A dataset wich will contain the resultset generatedby the command</param>
/// <paramname="tableNames">This array will be used to create table mappingsallowing the DataTables to be referenced
/// by a user defined name (probablythe actual table name)
/// </param>
/// <paramname="commandParameters">An array of SqlParamters used to executethe command</param>
private static voidFillDataset(SqlConnection connection, SqlTransaction transaction, CommandTypecommandType,
string commandText, DataSetdataSet, string[] tableNames,
params SqlParameter[]commandParameters)
{
if (connection == null) throw newArgumentNullException("connection");
if (dataSet == null) throw newArgumentNullException("dataSet");
// Create a command and prepare itfor execution
SqlCommand command = newSqlCommand();
bool mustCloseConnection = false;
PrepareCommand(command, connection,transaction, commandType, commandText, commandParameters, outmustCloseConnection);
// Create the DataAdapter &DataSet
using (SqlDataAdapter dataAdapter =new SqlDataAdapter(command))
{
// Add the table mappingsspecified by the user
if (tableNames != null&& tableNames.Length > 0)
{
string tableName ="Table";
for (int index = 0; index< tableNames.Length; index++)
{
if (tableNames[index]== null || tableNames[index].Length == 0) throw new ArgumentException("ThetableNames parameter must contain a list of tables, a value was provided asnull or empty string.", "tableNames");
dataAdapter.TableMappings.Add(tableName, tableNames[index]);
tableName += (index +1).ToString();
}
}
// Fill the DataSet usingdefault values for DataTable names, etc
dataAdapter.Fill(dataSet);
// Detach the SqlParametersfrom the command object, so they can be used again
command.Parameters.Clear();
}
if (mustCloseConnection)
connection.Close();
}
#endregion
#region UpdateDataset
/// <summary>
/// Executes the respective command foreach inserted, updated, or deleted row in the DataSet.
/// </summary>
/// <remarks>
/// e.g.:
/// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand,dataSet, "Order");
/// </remarks>
/// <paramname="insertCommand">A valid transact-SQL statement or storedprocedure to insert new records into the data source</param>
/// <paramname="deleteCommand">A valid transact-SQL statement or storedprocedure to delete records from the data source</param>
/// <paramname="updateCommand">A valid transact-SQL statement or storedprocedure used to update records in the data source</param>
/// <paramname="dataSet">The DataSet used to update the datasource</param>
/// <paramname="tableName">The DataTable used to update the datasource.</param>
internal static voidUpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommandupdateCommand, DataSet dataSet, string tableName)
{
if (insertCommand == null) thrownew ArgumentNullException("insertCommand");
if (deleteCommand == null) thrownew ArgumentNullException("deleteCommand");
if (updateCommand == null) thrownew ArgumentNullException("updateCommand");
if (tableName == null ||tableName.Length == 0) throw new ArgumentNullException("tableName");
// Create a SqlDataAdapter, anddispose of it after we are done
using (SqlDataAdapter dataAdapter =new SqlDataAdapter())
{
// Set the data adaptercommands
dataAdapter.UpdateCommand =updateCommand;
dataAdapter.InsertCommand =insertCommand;
dataAdapter.DeleteCommand =deleteCommand;
// Update the dataset changesin the data source
dataAdapter.Update(dataSet,tableName);
// Commit all the changes madeto the DataSet
dataSet.AcceptChanges();
}
}
#endregion
#region CreateCommand
/// <summary>
/// Simplify the creation of a Sqlcommand object by allowing
/// a stored procedure and optionalparameters to be provided
/// </summary>
/// <remarks>
/// e.g.:
/// SqlCommand command = CreateCommand(conn, "AddCustomer","CustomerID", "CustomerName");
/// </remarks>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="sourceColumns">An array of string to be assigned as thesource columns of the stored procedure parameters</param>
/// <returns>A valid SqlCommandobject</returns>
internal static SqlCommandCreateCommand(SqlConnection connection, string spName, params string[]sourceColumns)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// Create a SqlCommand
SqlCommand cmd = newSqlCommand(spName, connection);
cmd.CommandType =CommandType.StoredProcedure;
// If we receive parameter values,we need to figure out where they go
if ((sourceColumns != null)&& (sourceColumns.Length > 0))
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Assign the provided sourcecolumns to these parameters based on parameter order
for (int index = 0; index <sourceColumns.Length; index++)
commandParameters[index].SourceColumn = sourceColumns[index];
// Attach the discoveredparameters to the SqlCommand object
AttachParameters(cmd,commandParameters);
}
return cmd;
}
#endregion
#region ExecuteNonQueryTypedParams
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns no resultset) against the database specified in
/// the connection string using thedataRow column values as the stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on row values.
/// </summary>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQueryTypedParams(String connectionString, String spName, DataRowdataRow)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure,spName, commandParameters);
}
else
{
returnSqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure,spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns no resultset) against the specified SqlConnection
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on row values.
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRowdataRow)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns no resultset) against the specified
/// SqlTransaction using the dataRowcolumn values as the stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on row values.
/// </summary>
/// <paramname="transaction">A valid SqlTransaction object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An int representingthe number of rows affected by the command</returns>
internal static intExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRowdataRow)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// Sf the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteDatasetTypedParams
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the database specified in
/// the connection string using thedataRow column values as the stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on row values.
/// </summary>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDatasetTypedParams(string connectionString, String spName, DataRowdataRow)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
//If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure,spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the dataRow column values asthe store procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on row values.
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRowdataRow)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on row values.
/// </summary>
/// <paramname="transaction">A valid SqlTransaction object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>A dataset containingthe resultset generated by the command</returns>
internal static DataSetExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRowdataRow)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteReaderTypedParams
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the database specified in
/// the connection string using thedataRow column values as the stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReaderTypedParams(String connectionString, String spName, DataRowdataRow)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReaderTypedParams(SqlConnection connection, String spName, DataRowdataRow)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="transaction">A valid SqlTransaction object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>A SqlDataReadercontaining the resultset generated by the command</returns>
internal static SqlDataReaderExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRowdataRow)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteScalarTypedParams
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a 1x1 resultset) against the database specified in
/// the connection string using thedataRow column values as the stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalarTypedParams(String connectionString, String spName, DataRowdataRow)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalarTypedParams(SqlConnection connection, String spName, DataRowdataRow)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="transaction">A valid SqlTransaction object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An object containingthe value in the 1x1 resultset generated by the command</returns>
internal static objectExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRowdataRow)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteXmlReaderTypedParams
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlConnection
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRowdataRow)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection,spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
}
/// <summary>
/// Execute a stored procedure via aSqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the dataRow column values asthe stored procedure's parameters values.
/// This method will query the databaseto discover the parameters for the
/// stored procedure (the first timeeach stored procedure is called), and assign the values based on parameterorder.
/// </summary>
/// <paramname="transaction">A valid SqlTransaction object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="dataRow">The dataRow used to hold the stored procedure'sparameter values.</param>
/// <returns>An XmlReadercontaining the resultset generated by the command</returns>
internal static XmlReaderExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRowdataRow)
{
if (transaction == null) throw newArgumentNullException("transaction");
if (transaction != null &&transaction.Connection == null) throw new ArgumentException("Thetransaction was rollbacked or commited, please provide an opentransaction.", "transaction");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
// If the row has values, the storeprocedure parameters must be initialized
if (dataRow != null &&dataRow.ItemArray.Length > 0)
{
// Pull the parameters for thisstored procedure from the parameter cache (or discover them & populate thecache)
SqlParameter[]commandParameters =SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
// Set the parameters values
AssignParameterValues(commandParameters, dataRow);
returnSqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName,commandParameters);
}
else
{
returnSqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
}
/// <summary>
/// SqlHelperParameterCache providesfunctions to leverage a static cache of procedure parameters, and the
/// ability to discover parameters forstored procedures at run-time.
/// </summary>
internal sealed classSqlHelperParameterCache
{
#region private methods, variables, andconstructors
//Since this class provides only staticmethods, make the default constructor private to prevent
//instances from being created with"new SqlHelperParameterCache()"
private SqlHelperParameterCache() { }
private static Hashtable paramCache =Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Resolve at run time the appropriateset of SqlParameters for a stored procedure
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="includeReturnValueParameter">Whether or not to include theirreturn value parameter</param>
/// <returns>The parameter arraydiscovered.</returns>
private static SqlParameter[]DiscoverSpParameterSet(SqlConnection connection, string spName, boolincludeReturnValueParameter)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
SqlCommand cmd = newSqlCommand(spName, connection);
cmd.CommandType =CommandType.StoredProcedure;
connection.Open();
SqlCommandBuilder.DeriveParameters(cmd);
connection.Close();
if (!includeReturnValueParameter)
{
cmd.Parameters.RemoveAt(0);
}
SqlParameter[] discoveredParameters= new SqlParameter[cmd.Parameters.Count];
cmd.Parameters.CopyTo(discoveredParameters, 0);
// Init the parameters with aDBNull value
foreach (SqlParameterdiscoveredParameter in discoveredParameters)
{
discoveredParameter.Value =DBNull.Value;
}
return discoveredParameters;
}
/// <summary>
/// Deep copy of cached SqlParameterarray
/// </summary>
/// <paramname="originalParameters"></param>
/// <returns></returns>
private static SqlParameter[]CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] clonedParameters =new SqlParameter[originalParameters.Length];
for (int i = 0, j =originalParameters.Length; i < j; i++)
{
clonedParameters[i] =(SqlParameter)((ICloneable)originalParameters[i]).Clone();
}
return clonedParameters;
}
#endregion private methods, variables,and constructors
#region caching functions
/// <summary>
/// Add parameter array to the cache
/// </summary>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <paramname="commandParameters">An array of SqlParamters to becached</param>
internal static voidCacheParameterSet(string connectionString, string commandText, paramsSqlParameter[] commandParameters)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (commandText == null ||commandText.Length == 0) throw newArgumentNullException("commandText");
string hashKey = connectionString +":" + commandText;
paramCache[hashKey] =commandParameters;
}
/// <summary>
/// Retrieve a parameter array from thecache
/// </summary>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="commandText">The stored procedure name or T-SQLcommand</param>
/// <returns>An array ofSqlParamters</returns>
internal static SqlParameter[]GetCachedParameterSet(string connectionString, string commandText)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (commandText == null ||commandText.Length == 0) throw newArgumentNullException("commandText");
string hashKey = connectionString +":" + commandText;
SqlParameter[] cachedParameters =paramCache[hashKey] as SqlParameter[];
if (cachedParameters == null)
{
return null;
}
else
{
returnCloneParameters(cachedParameters);
}
}
#endregion caching functions
#region Parameter Discovery Functions
/// <summary>
/// Retrieves the set of SqlParametersappropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the databasefor this information, and then store it in a cache for future requests.
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <returns>An array ofSqlParameters</returns>
internal static SqlParameter[]GetSpParameterSet(string connectionString, string spName)
{
returnGetSpParameterSet(connectionString, spName, false);
}
/// <summary>
/// Retrieves the set of SqlParametersappropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the databasefor this information, and then store it in a cache for future requests.
/// </remarks>
/// <paramname="connectionString">A valid connection string for aSqlConnection</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="includeReturnValueParameter">A bool value indicating whetherthe return value parameter should be included in the results</param>
/// <returns>An array ofSqlParameters</returns>
internal static SqlParameter[]GetSpParameterSet(string connectionString, string spName, boolincludeReturnValueParameter)
{
if (connectionString == null ||connectionString.Length == 0) throw newArgumentNullException("connectionString");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
using (SqlConnection connection =new SqlConnection(connectionString))
{
returnGetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
}
}
/// <summary>
/// Retrieves the set of SqlParametersappropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the databasefor this information, and then store it in a cache for future requests.
/// </remarks>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <returns>An array ofSqlParameters</returns>
internal static SqlParameter[]GetSpParameterSet(SqlConnection connection, string spName)
{
returnGetSpParameterSet(connection, spName, false);
}
/// <summary>
/// Retrieves the set of SqlParametersappropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the databasefor this information, and then store it in a cache for future requests.
/// </remarks>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="includeReturnValueParameter">A bool value indicating whetherthe return value parameter should be included in the results</param>
/// <returns>An array ofSqlParameters</returns>
internal static SqlParameter[]GetSpParameterSet(SqlConnection connection, string spName, boolincludeReturnValueParameter)
{
if (connection == null) throw newArgumentNullException("connection");
using (SqlConnectionclonedConnection = (SqlConnection)((ICloneable)connection).Clone())
{
returnGetSpParameterSetInternal(clonedConnection, spName,includeReturnValueParameter);
}
}
/// <summary>
/// Retrieves the set of SqlParametersappropriate for the stored procedure
/// </summary>
/// <paramname="connection">A valid SqlConnection object</param>
/// <paramname="spName">The name of the stored procedure</param>
/// <paramname="includeReturnValueParameter">A bool value indicating whetherthe return value parameter should be included in the results</param>
/// <returns>An array ofSqlParameters</returns>
private static SqlParameter[]GetSpParameterSetInternal(SqlConnection connection, string spName, boolincludeReturnValueParameter)
{
if (connection == null) throw newArgumentNullException("connection");
if (spName == null || spName.Length== 0) throw new ArgumentNullException("spName");
string hashKey =connection.ConnectionString + ":" + spName +(includeReturnValueParameter ? ":include ReturnValue Parameter" :"");
SqlParameter[] cachedParameters;
cachedParameters =paramCache[hashKey] as SqlParameter[];
if (cachedParameters == null)
{
SqlParameter[] spParameters =DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
paramCache[hashKey] =spParameters;
cachedParameters =spParameters;
}
returnCloneParameters(cachedParameters);
}
#endregion Parameter DiscoveryFunctions
}
}
- 微软官方的SqlHelper
- 微软官方SqlHelper
- 微软官方的SQLHelper类(含完整中文注释)
- 微软官方的SQLHelper类(含完整中文注释)
- 微软sqlHelper
- 微软SQLHelper
- 微软的SQLHelper类
- 微软的SqlHelper类
- 微软sqlhelper.cs12312
- 微软完整的SQLHelper
- 微软原版SQLHelper类
- 微软C# SQLHelper类
- 微软SQLHelper.cs类 中文版
- 微软SQLHelper.cs类 中文版
- 微软SQLHelper.cs类 中文版
- 微软SQLHelper.cs类 中文版
- 微软SQLHelper.cs类 中文版
- 微软SQLHelper.cs类 中文版
- 【详解】简单验证码的解析
- Ajax中 async的作用
- 程序7——一棵二叉树是不是另外一棵二叉树的子结构
- [leetcdoe] 119. Pascal's Triangle II 解题报告
- 每天睡6小时和8小时的区别 【链接】
- 微软官方SqlHelper
- subgrid更新后刷新主表单
- 使用monyog监控mysql教程
- 3.2版本调用soapclient报错
- Java Web开发环境配置
- 百试不爽的面试经——咳咳,收到比亚迪面试通知的童鞋注意了
- Android基础之用Eclipse搭建Android开发环境和创建第一个Android项目(Windows平台)
- 计算器面向对象
- 角色 RESOURCE、CONNECT、DBA具有的权限