一,微软SQLHelper.cs类 中文版:

 using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections; namespace Classbao.Data
{
/// <summary>
/// SqlServer数据访问帮助类
/// </summary>
public sealed partial class SqlHelper
{
#region 私有构造函数和方法 private SqlHelper() { } /// <summary>
/// 将SqlParameter参数数组(参数值)分配给SqlCommand命令.
/// 这个方法将给任何一个参数分配DBNull.Value;
/// 该操作将阻止默认值的使用.
/// </summary>
/// <param name="command">命令名</param>
/// <param name="commandParameters">SqlParameters数组</param>
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("command");
if (commandParameters != null)
{
foreach (SqlParameter p in commandParameters)
{
if (p != null)
{
// 检查未分配值的输出参数,将其分配以DBNull.Value.
if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) &&
(p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
} /// <summary>
/// 将DataRow类型的列值分配到SqlParameter参数数组.
/// </summary>
/// <param name="commandParameters">要分配值的SqlParameter参数数组</param>
/// <param name="dataRow">将要分配给存储过程参数的DataRow</param>
private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
{
if ((commandParameters == null) || (dataRow == null))
{
return;
} int i = ;
// 设置参数值
foreach (SqlParameter commandParameter in commandParameters)
{
// 创建参数名称,如果不存在,只抛出一个异常.
if (commandParameter.ParameterName == null ||
commandParameter.ParameterName.Length <= )
throw new Exception(
string.Format("请提供参数{0}一个有效的名称{1}.", i, commandParameter.ParameterName));
// 从dataRow的表中获取为参数数组中数组名称的列的索引.
// 如果存在和参数名称相同的列,则将列值赋给当前名称的参数.
if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring()) != -)
commandParameter.Value = dataRow[commandParameter.ParameterName.Substring()];
i++;
}
} /// <summary>
/// 将一个对象数组分配给SqlParameter参数数组.
/// </summary>
/// <param name="commandParameters">要分配值的SqlParameter参数数组</param>
/// <param name="parameterValues">将要分配给存储过程参数的对象数组</param>
private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
return;
} // 确保对象数组个数与参数个数匹配,如果不匹配,抛出一个异常.
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("参数值个数与参数不匹配.");
} // 给参数赋值
for (int i = , j = commandParameters.Length; i < j; i++)
{
// If the current array value derives from IDbDataParameter, then assign its Value property
if (parameterValues[i] is IDbDataParameter)
{
IDbDataParameter paramInstance = (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>
/// 预处理用户提供的命令,数据库连接/事务/命令类型/参数
/// </summary>
/// <param name="command">要处理的SqlCommand</param>
/// <param name="connection">数据库连接</param>
/// <param name="transaction">一个有效的事务或者是null值</param>
/// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
/// <param name="commandText">存储过程名或都T-SQL命令文本</param>
/// <param name="commandParameters">和命令相关联的SqlParameter参数数组,如果没有参数为'null'</param>
/// <param name="mustCloseConnection"><c>true</c> 如果连接是打开的,则为true,其它情况下为false.</param>
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
{
if (command == null) throw new ArgumentNullException("command");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); // If the provided connection is not open, we will open it
if (connection.State != ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
} // 给命令分配一个数据库连接.
command.Connection = connection; // 设置命令文本(存储过程名或SQL语句)
command.CommandText = commandText; // 分配事务
if (transaction != null)
{
if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
command.Transaction = transaction;
} // 设置命令类型.
command.CommandType = commandType; // 分配命令参数
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
} #endregion 私有构造函数和方法结束 #region ExecuteNonQuery命令 /// <summary>
/// 执行指定连接字符串,类型的SqlCommand.
/// </summary>
/// <remarks>
/// 示例:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
/// <param name="commandText">存储过程名称或SQL语句</param>
/// <returns>返回命令影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
{
return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定连接字符串,类型的SqlCommand.如果没有提供参数,不返回结果.
/// </summary>
/// <remarks>
/// 示例:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
/// <param name="commandText">存储过程名称或SQL语句</param>
/// <param name="commandParameters">SqlParameter参数数组</param>
/// <returns>返回命令影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString"); using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
}
} /// <summary>
/// 执行指定连接字符串的存储过程,将对象数组的值赋给存储过程参数,
/// 此方法需要在参数缓存方法中探索参数并生成参数.
/// </summary>
/// <remarks>
/// 这个方法没有提供访问输出参数和返回值.
/// 示例:
/// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串/param>
/// <param name="spName">存储过程名称</param>
/// <param name="parameterValues">分配到存储过程输入参数的对象数组</param>
/// <returns>返回受影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果存在参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从探索存储过程参数(加载到缓存)并分配给存储过程参数数组.
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数情况下
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定数据库连接对象的命令
/// </summary>
/// <remarks>
/// 示例:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接对象的命令
/// </summary>
/// <remarks>
/// 示例:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
/// <param name="commandText">T存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">SqlParamter参数数组</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); // 创建SqlCommand命令,并进行预处理
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // Finally, execute the command
int retval = cmd.ExecuteNonQuery(); // 清除参数,以便再次使用.
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
} /// <summary>
/// 执行指定数据库连接对象的命令,将对象数组的值赋给存储过程参数.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值
/// 示例:
/// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程分配参数值
AssignParameterValues(commandParameters, parameterValues); return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行带事务的SqlCommand.
/// </summary>
/// <remarks>
/// 示例.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="transaction">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回影响的行数/returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行带事务的SqlCommand(指定参数).
/// </summary>
/// <remarks>
/// 示例:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">SqlParamter参数数组</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 预处理
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行
int retval = cmd.ExecuteNonQuery(); // 清除参数集,以便再次使用.
cmd.Parameters.Clear();
return retval;
} /// <summary>
/// 执行带事务的SqlCommand(指定参数值).
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值
/// 示例:
/// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="transaction">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回受影响的行数</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteNonQuery方法结束 #region ExecuteDataset方法 /// <summary>
/// 执行指定数据库连接字符串的命令,返回DataSet.
/// </summary>
/// <remarks>
/// 示例:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
{
return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接字符串的命令,返回DataSet.
/// </summary>
/// <remarks>
/// 示例:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">SqlParamters参数数组</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString"); // 创建并打开数据库连接对象,操作完成释放对象.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // 调用指定数据库连接字符串重载方法.
return ExecuteDataset(connection, commandType, commandText, commandParameters);
}
} /// <summary>
/// 执行指定数据库连接字符串的命令,直接提供参数值,返回DataSet.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值.
/// 示例:
/// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中检索存储过程参数
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 给存储过程参数分配值
AssignParameterValues(commandParameters, parameterValues); return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定数据库连接对象的命令,返回DataSet.
/// </summary>
/// <remarks>
/// 示例:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接对象的命令,指定存储过程参数,返回DataSet.
/// </summary>
/// <remarks>
/// 示例:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <param name="commandParameters">SqlParamter参数数组</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); // 预处理
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // 创建SqlDataAdapter和DataSet.
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet(); // 填充DataSet.
da.Fill(ds); cmd.Parameters.Clear(); if (mustCloseConnection)
connection.Close(); return ds;
}
} /// <summary>
/// 执行指定数据库连接对象的命令,指定参数值,返回DataSet.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输入参数和返回值.
/// 示例.:
/// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > ))
{
// 比缓存中加载存储过程参数
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数分配值
AssignParameterValues(commandParameters, parameterValues); return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定事务的命令,返回DataSet.
/// </summary>
/// <remarks>
/// 示例:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定事务的命令,指定参数,返回DataSet.
/// </summary>
/// <remarks>
/// 示例:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <param name="commandParameters">SqlParamter参数数组</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 预处理
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 创建 DataAdapter & DataSet
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
} /// <summary>
/// 执行指定事务的命令,指定参数值,返回DataSet.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输入参数和返回值.
/// 示例.:
/// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">事务</param>
/// <param name="spName">存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回一个包含结果集的DataSet</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数分配值
AssignParameterValues(commandParameters, parameterValues); return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteDataset数据集命令结束 #region ExecuteReader 数据阅读器 /// <summary>
/// 枚举,标识数据库连接是由SqlHelper提供还是由调用者提供
/// </summary>
private enum SqlConnectionOwnership
{
/// <summary>由SqlHelper提供连接</summary>
Internal,
/// <summary>由调用者提供连接</summary>
External
} /// <summary>
/// 执行指定数据库连接对象的数据阅读器.
/// </summary>
/// <remarks>
/// 如果是SqlHelper打开连接,当连接关闭DataReader也将关闭.
/// 如果是调用都打开连接,DataReader由调用都管理.
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="transaction">一个有效的事务,或者为 'null'</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <param name="commandParameters">SqlParameters参数数组,如果没有参数则为'null'</param>
/// <param name="connectionOwnership">标识数据库连接对象是由调用者提供还是由SqlHelper提供</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
{
if (connection == null) throw new ArgumentNullException("connection"); bool mustCloseConnection = false;
// 创建命令
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 创建数据阅读器
SqlDataReader dataReader; if (connectionOwnership == SqlConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
} // 清除参数,以便再次使用..
// HACK: There is a problem here, the output parameter values are fletched
// when the reader is closed, so if the parameters are detached from the command
// then the SqlReader can磘 set its values.
// When this happen, the parameters can磘 be used again in other command.
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
canClear = false;
} if (canClear)
{
cmd.Parameters.Clear();
} return dataReader;
}
catch
{
if (mustCloseConnection)
connection.Close();
throw;
}
} /// <summary>
/// 执行指定数据库连接字符串的数据阅读器.
/// </summary>
/// <remarks>
/// 示例:
/// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
{
return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接字符串的数据阅读器,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <param name="commandParameters">SqlParamter参数数组(new SqlParameter("@prodid", 24))</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open(); return ExecuteReader(connection, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal);
}
catch
{
// If we fail to return the SqlDatReader, we need to close the connection ourselves
if (connection != null) connection.Close();
throw;
} } /// <summary>
/// 执行指定数据库连接字符串的数据阅读器,指定参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
/// 示例:
/// SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > ))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定数据库连接对象的数据阅读器.
/// </summary>
/// <remarks>
/// 示例:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名或T-SQL语句</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// [调用者方式]执行指定数据库连接对象的数据阅读器,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandParameters">SqlParamter参数数组</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
} /// <summary>
/// [调用者方式]执行指定数据库连接对象的数据阅读器,指定参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
/// 示例:
/// SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">T存储过程名</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > ))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// [调用者方式]执行指定数据库事务的数据阅读器,指定参数值.
/// </summary>
/// <remarks>
/// 示例:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// [调用者方式]执行指定数据库事务的数据阅读器,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
} /// <summary>
/// [调用者方式]执行指定数据库事务的数据阅读器,指定参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="spName">存储过程名称</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteReader数据阅读器 #region ExecuteScalar 返回结果集中的第一行第一列 /// <summary>
/// 执行指定数据库连接字符串的命令,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 示例:
/// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
{
// 执行参数为空的方法
return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接字符串的命令,指定参数,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 示例:
/// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
// 创建并打开数据库连接对象,操作完成释放对象.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // 调用指定数据库连接字符串重载方法.
return ExecuteScalar(connection, commandType, commandText, commandParameters);
}
} /// <summary>
/// 执行指定数据库连接字符串的命令,指定参数值,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名称</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定数据库连接对象的命令,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 示例:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
{
// 执行参数为空的方法
return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接对象的命令,指定参数,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 示例:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); // 创建SqlCommand命令,并进行预处理
SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // 执行SqlCommand命令,并返回结果.
object retval = cmd.ExecuteScalar(); // 清除参数,以便再次使用.
cmd.Parameters.Clear(); if (mustCloseConnection)
connection.Close(); return retval;
} /// <summary>
/// 执行指定数据库连接对象的命令,指定参数值,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定数据库事务的命令,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 示例:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
{
// 执行参数为空的方法
return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库事务的命令,指定参数,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 示例:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 创建SqlCommand命令,并进行预处理
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行SqlCommand命令,并返回结果.
object retval = cmd.ExecuteScalar(); // 清除参数,以便再次使用.
cmd.Parameters.Clear();
return retval;
} /// <summary>
/// 执行指定数据库事务的命令,指定参数值,返回结果集中的第一行第一列.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="spName">存储过程名称</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// PPull the parameters for this stored procedure from the parameter cache ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteScalar #region ExecuteXmlReader XML阅读器
/// <summary>
/// 执行指定数据库连接对象的SqlCommand命令,并产生一个XmlReader对象做为结果集返回.
/// </summary>
/// <remarks>
/// 示例:
/// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
{
// 执行参数为空的方法
return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库连接对象的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); bool mustCloseConnection = false;
// 创建SqlCommand命令,并进行预处理
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // 执行命令
XmlReader retval = cmd.ExecuteXmlReader(); // 清除参数,以便再次使用.
cmd.Parameters.Clear(); return retval;
}
catch
{
if (mustCloseConnection)
connection.Close();
throw;
}
} /// <summary>
/// 执行指定数据库连接对象的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称 using "FOR XML AUTO"</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定数据库事务的SqlCommand命令,并产生一个XmlReader对象做为结果集返回.
/// </summary>
/// <remarks>
/// 示例:
/// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
// 执行参数为空的方法
return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// 执行指定数据库事务的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 创建SqlCommand命令,并进行预处理
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行命令
XmlReader retval = cmd.ExecuteXmlReader(); // 清除参数,以便再次使用.
cmd.Parameters.Clear();
return retval;
} /// <summary>
/// 执行指定数据库事务的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="spName">存储过程名称</param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
/// <returns>返回一个包含结果集的DataSet.</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// 没有参数值
return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteXmlReader 阅读器结束 #region FillDataset 填充数据集
/// <summary>
/// 执行指定数据库连接字符串的命令,映射数据表并填充数据集.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)</param>
public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (dataSet == null) throw new ArgumentNullException("dataSet"); // 创建并打开数据库连接对象,操作完成释放对象.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // 调用指定数据库连接字符串重载方法.
FillDataset(connection, commandType, commandText, dataSet, tableNames);
}
} /// <summary>
/// 执行指定数据库连接字符串的命令,映射数据表并填充数据集.指定命令参数.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
public static void FillDataset(string connectionString, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (dataSet == null) throw new ArgumentNullException("dataSet");
// 创建并打开数据库连接对象,操作完成释放对象.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // 调用指定数据库连接字符串重载方法.
FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
}
} /// <summary>
/// 执行指定数据库连接字符串的命令,映射数据表并填充数据集,指定存储过程参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, 24);
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
public static void FillDataset(string connectionString, string spName,
DataSet dataSet, string[] tableNames,
params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (dataSet == null) throw new ArgumentNullException("dataSet");
// 创建并打开数据库连接对象,操作完成释放对象.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // 调用指定数据库连接字符串重载方法.
FillDataset(connection, spName, dataSet, tableNames, parameterValues);
}
} /// <summary>
/// 执行指定数据库连接对象的命令,映射数据表并填充数据集.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
public static void FillDataset(SqlConnection connection, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames)
{
FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
} /// <summary>
/// 执行指定数据库连接对象的命令,映射数据表并填充数据集,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
public static void FillDataset(SqlConnection connection, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
} /// <summary>
/// 执行指定数据库连接对象的命令,映射数据表并填充数据集,指定存储过程参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, 24, 36);
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
public static void FillDataset(SqlConnection connection, string spName,
DataSet dataSet, string[] tableNames,
params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (dataSet == null) throw new ArgumentNullException("dataSet");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
// 没有参数值
FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
}
} /// <summary>
/// 执行指定数据库事务的命令,映射数据表并填充数据集.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
public static void FillDataset(SqlTransaction transaction, CommandType commandType,
string commandText,
DataSet dataSet, string[] tableNames)
{
FillDataset(transaction, commandType, commandText, dataSet, tableNames, null);
} /// <summary>
/// 执行指定数据库事务的命令,映射数据表并填充数据集,指定参数.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
public static void FillDataset(SqlTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
} /// <summary>
/// 执行指定数据库事务的命令,映射数据表并填充数据集,指定存储过程参数值.
/// </summary>
/// <remarks>
/// 此方法不提供访问存储过程输出参数和返回值参数.
///
/// 示例:
/// FillDataset(trans, "GetOrders", ds, new string[]{"orders"}, 24, 36);
/// </remarks>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
/// <param name="parameterValues">分配给存储过程输入参数的对象数组</param>
public static void FillDataset(SqlTransaction transaction, string spName,
DataSet dataSet, string[] tableNames,
params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (dataSet == null) throw new ArgumentNullException("dataSet");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果有参数值
if ((parameterValues != null) && (parameterValues.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值
AssignParameterValues(commandParameters, parameterValues); // 调用重载方法
FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
// 没有参数值
FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
}
} /// <summary>
/// [私有方法][内部调用]执行指定数据库连接对象/事务的命令,映射数据表并填充数据集,DataSet/TableNames/SqlParameters.
/// </summary>
/// <remarks>
/// 示例:
/// FillDataset(conn, trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="transaction">一个有效的连接事务</param>
/// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
/// <param name="commandText">存储过程名称或T-SQL语句</param>
/// <param name="dataSet">要填充结果集的DataSet实例</param>
/// <param name="tableNames">表映射的数据表数组
/// 用户定义的表名 (可有是实际的表名.)
/// </param>
/// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
if (dataSet == null) throw new ArgumentNullException("dataSet"); // 创建SqlCommand命令,并进行预处理
SqlCommand command = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行命令
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{ // 追加表映射
if (tableNames != null && tableNames.Length > )
{
string tableName = "Table";
for (int index = ; index < tableNames.Length; index++)
{
if (tableNames[index] == null || tableNames[index].Length == ) throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames");
dataAdapter.TableMappings.Add(tableName, tableNames[index]);
tableName += (index + ).ToString();
}
} // 填充数据集使用默认表名称
dataAdapter.Fill(dataSet); // 清除参数,以便再次使用.
command.Parameters.Clear();
} if (mustCloseConnection)
connection.Close();
}
#endregion #region UpdateDataset 更新数据集
/// <summary>
/// 执行数据集更新到数据库,指定inserted, updated, or deleted命令.
/// </summary>
/// <remarks>
/// 示例:
/// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
/// </remarks>
/// <param name="insertCommand">[追加记录]一个有效的T-SQL语句或存储过程</param>
/// <param name="deleteCommand">[删除记录]一个有效的T-SQL语句或存储过程</param>
/// <param name="updateCommand">[更新记录]一个有效的T-SQL语句或存储过程</param>
/// <param name="dataSet">要更新到数据库的DataSet</param>
/// <param name="tableName">要更新到数据库的DataTable</param>
public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
{
if (insertCommand == null) throw new ArgumentNullException("insertCommand");
if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
if (updateCommand == null) throw new ArgumentNullException("updateCommand");
if (tableName == null || tableName.Length == ) throw new ArgumentNullException("tableName"); // 创建SqlDataAdapter,当操作完成后释放.
using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
{
// 设置数据适配器命令
dataAdapter.UpdateCommand = updateCommand;
dataAdapter.InsertCommand = insertCommand;
dataAdapter.DeleteCommand = deleteCommand; // 更新数据集改变到数据库
dataAdapter.Update(dataSet, tableName); // 提交所有改变到数据集.
dataSet.AcceptChanges();
}
}
#endregion #region CreateCommand 创建一条SqlCommand命令
/// <summary>
/// 创建SqlCommand命令,指定数据库连接对象,存储过程名和参数.
/// </summary>
/// <remarks>
/// 示例:
/// SqlCommand command = CreateCommand(conn, "AddCustomer", "CustomerID", "CustomerName");
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="sourceColumns">源表的列名称数组</param>
/// <returns>返回SqlCommand命令</returns>
public static SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 创建命令
SqlCommand cmd = new SqlCommand(spName, connection);
cmd.CommandType = CommandType.StoredProcedure; // 如果有参数值
if ((sourceColumns != null) && (sourceColumns.Length > ))
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 将源表的列到映射到DataSet命令中.
for (int index = ; index < sourceColumns.Length; index++)
commandParameters[index].SourceColumn = sourceColumns[index]; // Attach the discovered parameters to the SqlCommand object
AttachParameters(cmd, commandParameters);
} return cmd;
}
#endregion #region ExecuteNonQueryTypedParams 类型化参数(DataRow)
/// <summary>
/// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回受影响的行数.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回受影响的行数.
/// </summary>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库事物的存储过程,使用DataRow做为参数值,返回受影响的行数.
/// </summary>
/// <param name="transaction">一个有效的连接事务 object</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // Sf the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion #region ExecuteDatasetTypedParams 类型化参数(DataRow)
/// <summary>
/// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回DataSet.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回一个包含结果集的DataSet.</returns>
public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); //如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回DataSet.
/// </summary>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回一个包含结果集的DataSet.</returns>
///
public static DataSet ExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库事务的存储过程,使用DataRow做为参数值,返回DataSet.
/// </summary>
/// <param name="transaction">一个有效的连接事务 object</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回一个包含结果集的DataSet.</returns>
public static DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
} #endregion #region ExecuteReaderTypedParams 类型化参数(DataRow)
/// <summary>
/// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回DataReader.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回DataReader.
/// </summary>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库事物的存储过程,使用DataRow做为参数值,返回DataReader.
/// </summary>
/// <param name="transaction">一个有效的连接事务 object</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回包含结果集的SqlDataReader</returns>
public static SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion #region ExecuteScalarTypedParams 类型化参数(DataRow)
/// <summary>
/// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回结果集中的第一行第一列.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回结果集中的第一行第一列.
/// </summary>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalarTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库事务的存储过程,使用DataRow做为参数值,返回结果集中的第一行第一列.
/// </summary>
/// <param name="transaction">一个有效的连接事务 object</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion #region ExecuteXmlReaderTypedParams 类型化参数(DataRow)
/// <summary>
/// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回XmlReader类型的结果集.
/// </summary>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// 执行指定连接数据库事务的存储过程,使用DataRow做为参数值,返回XmlReader类型的结果集.
/// </summary>
/// <param name="transaction">一个有效的连接事务 object</param>
/// <param name="spName">存储过程名称</param>
/// <param name="dataRow">使用DataRow作为参数值</param>
/// <returns>返回XmlReader结果集对象.</returns>
public static XmlReader ExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化.
if (dataRow != null && dataRow.ItemArray.Length > )
{
// 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. ()
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion } /// <summary>
/// SqlHelperParameterCache提供缓存存储过程参数,并能够在运行时从存储过程中探索参数.
/// </summary>
public sealed class SqlHelperParameterCache
{
#region 私有方法,字段,构造函数
// 私有构造函数,妨止类被实例化.
private SqlHelperParameterCache() { } // 这个方法要注意
private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable()); /// <summary>
/// 探索运行时的存储过程,返回SqlParameter参数数组.
/// 初始化参数值为 DBNull.Value.
/// </summary>
/// <param name="connection">一个有效的数据库连接</param>
/// <param name="spName">存储过程名称</param>
/// <param name="includeReturnValueParameter">是否包含返回值参数</param>
/// <returns>返回SqlParameter参数数组</returns>
private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); SqlCommand cmd = new SqlCommand(spName, connection);
cmd.CommandType = CommandType.StoredProcedure; connection.Open();
// 检索cmd指定的存储过程的参数信息,并填充到cmd的Parameters参数集中.
SqlCommandBuilder.DeriveParameters(cmd);
connection.Close();
// 如果不包含返回值参数,将参数集中的每一个参数删除.
if (!includeReturnValueParameter)
{
cmd.Parameters.RemoveAt();
} // 创建参数数组
SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];
// 将cmd的Parameters参数集复制到discoveredParameters数组.
cmd.Parameters.CopyTo(discoveredParameters, ); // 初始化参数值为 DBNull.Value.
foreach (SqlParameter discoveredParameter in discoveredParameters)
{
discoveredParameter.Value = DBNull.Value;
}
return discoveredParameters;
} /// <summary>
/// SqlParameter参数数组的深层拷贝.
/// </summary>
/// <param name="originalParameters">原始参数数组</param>
/// <returns>返回一个同样的参数数组</returns>
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length]; for (int i = , j = originalParameters.Length; i < j; i++)
{
clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
} return clonedParameters;
} #endregion 私有方法,字段,构造函数结束 #region 缓存方法 /// <summary>
/// 追加参数数组到缓存.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandText">存储过程名或SQL语句</param>
/// <param name="commandParameters">要缓存的参数数组</param>
public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; paramCache[hashKey] = commandParameters;
} /// <summary>
/// 从缓存中获取参数数组.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符</param>
/// <param name="commandText">存储过程名或SQL语句</param>
/// <returns>参数数组</returns>
public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
if (cachedParameters == null)
{
return null;
}
else
{
return CloneParameters(cachedParameters);
}
} #endregion 缓存方法结束 #region 检索指定的存储过程的参数集 /// <summary>
/// 返回指定的存储过程的参数集
/// </summary>
/// <remarks>
/// 这个方法将查询数据库,并将信息存储到缓存.
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符</param>
/// <param name="spName">存储过程名</param>
/// <returns>返回SqlParameter参数数组</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
{
return GetSpParameterSet(connectionString, spName, false);
} /// <summary>
/// 返回指定的存储过程的参数集
/// </summary>
/// <remarks>
/// 这个方法将查询数据库,并将信息存储到缓存.
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符.</param>
/// <param name="spName">存储过程名</param>
/// <param name="includeReturnValueParameter">是否包含返回值参数</param>
/// <returns>返回SqlParameter参数数组</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); using (SqlConnection connection = new SqlConnection(connectionString))
{
return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
}
} /// <summary>
/// [内部]返回指定的存储过程的参数集(使用连接对象).
/// </summary>
/// <remarks>
/// 这个方法将查询数据库,并将信息存储到缓存.
/// </remarks>
/// <param name="connection">一个有效的数据库连接字符</param>
/// <param name="spName">存储过程名</param>
/// <returns>返回SqlParameter参数数组</returns>
internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
{
return GetSpParameterSet(connection, spName, false);
} /// <summary>
/// [内部]返回指定的存储过程的参数集(使用连接对象)
/// </summary>
/// <remarks>
/// 这个方法将查询数据库,并将信息存储到缓存.
/// </remarks>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名</param>
/// <param name="includeReturnValueParameter">
/// 是否包含返回值参数
/// </param>
/// <returns>返回SqlParameter参数数组</returns>
internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
if (connection == null) throw new ArgumentNullException("connection");
using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone())
{
return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
}
} /// <summary>
/// [私有]返回指定的存储过程的参数集(使用连接对象)
/// </summary>
/// <param name="connection">一个有效的数据库连接对象</param>
/// <param name="spName">存储过程名</param>
/// <param name="includeReturnValueParameter">是否包含返回值参数</param>
/// <returns>返回SqlParameter参数数组</returns>
private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) 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;
} return CloneParameters(cachedParameters);
} #endregion 参数集检索结束 }
}

二,微软版的SqlHelper.cs类:

 // ===============================================================================
// Thanks for Microsoft Data Access Application Block team
// We use the SqlHelper2.0 in the ClassbaoFramework
// Xiongzaiqiren.Hero
//================================================================================ //
// Microsoft Data Access Application Block for .NET
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//
// SQLHelper.cs
//
// This file contains the implementations of the SqlHelper and SqlHelperParameterCache
// classes.
//
// For more information see the Data Access Application Block Implementation Overview.
// ===============================================================================
// Release history
// VERSION DESCRIPTION
// 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods
//
// ===============================================================================
// Copyright (C) 2000-2001 Microsoft Corporation
// All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
// ============================================================================== using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections; namespace Classbao.Data
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
/// common uses of SqlClient
/// </summary>
public sealed partial class SqlHelper
{
// // decrypt the ConnectionString #region private utility methods & constructors // Since this class provides only static methods, make the default constructor private to prevent
// instances from being created with "new SqlHelper()"
private SqlHelper() { } /// <summary>
/// This method is used to attach array of SqlParameters to a SqlCommand.
///
/// This method will assign a value of DbNull to any parameter with a direction of
/// InputOutput and a value of null.
///
/// This behavior will prevent default values from being used, but
/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
/// where the user provided no input value.
/// </summary>
/// <param name="command">The command to which the parameters will be added</param>
/// <param name="commandParameters">An array of SqlParameters to be added to command</param>
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("command");
if (commandParameters != null)
{
foreach (SqlParameter p in commandParameters)
{
if (p != null)
{
// Check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput ||
p.Direction == ParameterDirection.Input) &&
(p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
} /// <summary>
/// This method assigns dataRow column values to an array of SqlParameters
/// </summary>
/// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
{
if ((commandParameters == null) || (dataRow == null))
{
// Do nothing if we get no data
return;
} int i = ;
// Set the parameters values
foreach (SqlParameter commandParameter in commandParameters)
{
// Check the parameter name
if (commandParameter.ParameterName == null ||
commandParameter.ParameterName.Length <= )
throw new Exception(
string.Format(
"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
i, commandParameter.ParameterName));
if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring()) != -)
commandParameter.Value = dataRow[commandParameter.ParameterName.Substring()];
i++;
}
} /// <summary>
/// This method assigns an array of values to an array of SqlParameters
/// </summary>
/// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
/// <param name="parameterValues">Array of objects holding the values to be assigned</param>
private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
// Do nothing if we get no data
return;
} // We must have the same number of values as we pave parameters to put them in
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
} // Iterate through the SqlParameters, assigning the values from the corresponding position in the
// value array
for (int i = , j = commandParameters.Length; i < j; i++)
{
// If the current array value derives from IDbDataParameter, then assign its Value property
if (parameterValues[i] is IDbDataParameter)
{
IDbDataParameter paramInstance = (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>
/// <param name="command">The SqlCommand to be prepared</param>
/// <param name="connection">A valid SqlConnection, on which to execute this command</param>
/// <param name="transaction">A valid SqlTransaction, or 'null'</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
{
if (command == null) throw new ArgumentNullException("command");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); // If the provided connection is not open, we will open it
if (connection.State != ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
} // Associate the connection with the command
command.Connection = connection; // Set the command text (stored procedure name or SQL statement)
command.CommandText = commandText; // If we were provided a transaction, assign it
if (transaction != null)
{
if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
command.Transaction = transaction;
} // Set the command type
command.CommandType = commandType; // Attach the command parameters if they are provided
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
} #endregion private utility methods & constructors #region ExecuteNonQuery /// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
/// the connection string
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns no 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>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="timeout">The timeout time of command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteNonQuery(connectionString, commandType, commandText, -, commandParameters);
} /// <summary>
/// Execute a SqlCommand (that returns no 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>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="timeout">The timeout time of command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, int timeout, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString"); // Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Call the overload that takes a connection in place of the connection string
return ExecuteNonQuery(connection, commandType, commandText, timeout, commandParameters);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored prcedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns no 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteNonQuery(connection, commandType, commandText, -, commandParameters);
} /// <summary>
/// Execute a SqlCommand (that returns no 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="timeout">The timeout time of command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, int timeout, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); // Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand(); // Setting a timeout value for the SQL command. Setting timeout to zero means never time out,
// which we never want to do. If value passed in is undesired, then simply don't set this parameter
// and let it default to 30 seconds (according to MSDN).
if ((timeout != null) && (timeout >= ))
{
cmd.CommandTimeout = timeout;
} bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // Finally, execute the command
int retval = cmd.ExecuteNonQuery(); // Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
/// using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns no 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>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Create a command and prepare it for execution
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 from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteNonQuery #region ExecuteDataset /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteDataset(connectionString, commandType, commandText, -, commandParameters);
} /// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="timeout">Timeout value for the SQL command in seconds</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, int timeout, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString"); // Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Call the overload that takes a connection in place of the connection string
return ExecuteDataset(connection, commandType, commandText, timeout, commandParameters);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteDataset(connection, commandType, commandText, -, commandParameters);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="timeout">Timeout value for the SQL command in seconds</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, int timeout, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); // Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand(); // Setting a timeout value for the SQL command. Setting timeout to zero means never time out,
// which we never want to do. If value passed in is undesired, then simply don't set this parameter
// and let it default to 30 seconds (according to MSDN).
if ((timeout != null) && (timeout >= ))
{
cmd.CommandTimeout = timeout;
} bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // Create the DataAdapter & DataSet
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet(); // Fill the DataSet using default values for DataTable names, etc
da.Fill(ds); // Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear(); if (mustCloseConnection)
connection.Close(); // Return the dataset
return ds;
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // Create the DataAdapter & DataSet
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet(); // Fill the DataSet using default values for DataTable names, etc
da.Fill(ds); // Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear(); // Return the dataset
return ds;
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteDataset #region ExecuteReader /// <summary>
/// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
/// we can set the appropriate CommandBehavior when calling ExecuteReader()
/// </summary>
private enum SqlConnectionOwnership
{
/// <summary>Connection is owned and managed by SqlHelper</summary>
Internal,
/// <summary>Connection is owned 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 the connection, we want the connection to be closed when the DataReader is closed.
///
/// If the caller provided the connection, we want to leave it to them to manage.
/// </remarks>
/// <param name="connection">A valid SqlConnection, on which to execute this command</param>
/// <param name="transaction">A valid SqlTransaction, or 'null'</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
/// <returns>SqlDataReader containing the results of the command</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
{
if (connection == null) throw new ArgumentNullException("connection"); bool mustCloseConnection = false;
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // Create a reader
SqlDataReader dataReader; // Call ExecuteReader with the appropriate CommandBehavior
if (connectionOwnership == SqlConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
} // Detach the SqlParameters from the command object, so they can be used again.
// HACK: There is a problem here, the output parameter values are fletched
// when the reader is closed, so if the parameters are detached from the command
// then the SqlReader can磘 set its values.
// When this happen, the parameters can磘 be used again in other command.
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
canClear = false;
} if (canClear)
{
cmd.Parameters.Clear();
} return dataReader;
}
catch
{
if (mustCloseConnection)
connection.Close();
throw;
}
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open(); // Call the private overload that takes an internally owned connection in place of the connection string
return ExecuteReader(connection, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal);
}
catch
{
// If we fail to return the SqlDatReader, we need to close the connection ourselves
if (connection != null) connection.Close();
throw;
} } /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
// Pass through the call to the private overload using a null transaction value and an externally owned connection
return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Pass through to private overload, indicating that the connection is owned by the caller
return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteReader #region ExecuteScalar /// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Call the overload that takes a connection in place of the connection string
return ExecuteScalar(connection, commandType, commandText, commandParameters);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); // Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // Execute the command & return the results
object retval = cmd.ExecuteScalar(); // Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear(); if (mustCloseConnection)
connection.Close(); return retval;
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // Execute the command & return the results
object retval = cmd.ExecuteScalar(); // Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified
/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// PPull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteScalar #region ExecuteXmlReader
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection"); bool mustCloseConnection = false;
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // Create the DataAdapter & DataSet
XmlReader retval = cmd.ExecuteXmlReader(); // Detach the SqlParameters from 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 a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="spName">The name of the stored procedure using "FOR XML AUTO"</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Create a command and prepare it for execution
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 from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
} #endregion ExecuteXmlReader #region FillDataset
/// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)</param>
public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (dataSet == null) throw new ArgumentNullException("dataSet"); // Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Call the overload that takes a connection in place of the connection string
FillDataset(connection, commandType, commandText, dataSet, tableNames);
}
} /// <summary>
/// Execute a SqlCommand (that returns a 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"}, new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
public static void FillDataset(string connectionString, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (dataSet == null) throw new ArgumentNullException("dataSet");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Call the overload that takes a connection in place of the connection string
FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, 24);
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
public static void FillDataset(string connectionString, string spName,
DataSet dataSet, string[] tableNames,
params object[] parameterValues)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (dataSet == null) throw new ArgumentNullException("dataSet");
// Create & open a SqlConnection, and dispose of it after we are done
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // Call the overload that takes a connection in place of the connection string
FillDataset(connection, spName, dataSet, tableNames, parameterValues);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
public static void FillDataset(SqlConnection connection, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames)
{
FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
public static void FillDataset(SqlConnection connection, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, 24, 36);
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
public static void FillDataset(SqlConnection connection, string spName,
DataSet dataSet, string[] tableNames,
params object[] parameterValues)
{
if (connection == null) throw new ArgumentNullException("connection");
if (dataSet == null) throw new ArgumentNullException("dataSet");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
}
} /// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
public static void FillDataset(SqlTransaction transaction, CommandType commandType,
string commandText,
DataSet dataSet, string[] tableNames)
{
FillDataset(transaction, commandType, commandText, dataSet, tableNames, null);
} /// <summary>
/// Execute a SqlCommand (that returns a 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>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
public static void FillDataset(SqlTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// FillDataset(trans, "GetOrders", ds, new string[]{"orders"}, 24, 36);
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
public static void FillDataset(SqlTransaction transaction, string spName,
DataSet dataSet, string[] tableNames,
params object[] parameterValues)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (dataSet == null) throw new ArgumentNullException("dataSet");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues); // Call the overload that takes an array of SqlParameters
FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
// Otherwise we can just call the SP without params
FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
}
} /// <summary>
/// Private helper method that execute a SqlCommand (that returns a resultset) against the specified SqlTransaction and SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(conn, trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
/// by a user defined name (probably the actual table name)
/// </param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
if (dataSet == null) throw new ArgumentNullException("dataSet"); // Create a command and prepare it for execution
SqlCommand command = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // Create the DataAdapter & DataSet
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{ // Add the table mappings specified by the user
if (tableNames != null && tableNames.Length > )
{
string tableName = "Table";
for (int index = ; index < tableNames.Length; index++)
{
if (tableNames[index] == null || tableNames[index].Length == ) throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames");
dataAdapter.TableMappings.Add(tableName, tableNames[index]);
tableName += (index + ).ToString();
}
} // Fill the DataSet using default values for DataTable names, etc
dataAdapter.Fill(dataSet); // Detach the SqlParameters from the command object, so they can be used again
command.Parameters.Clear();
} if (mustCloseConnection)
connection.Close();
}
#endregion #region UpdateDataset
/// <summary>
/// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
/// </summary>
/// <remarks>
/// e.g.:
/// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
/// </remarks>
/// <param name="insertCommand">A valid transact-SQL statement or stored procedure to insert new records into the data source</param>
/// <param name="deleteCommand">A valid transact-SQL statement or stored procedure to delete records from the data source</param>
/// <param name="updateCommand">A valid transact-SQL statement or stored procedure used to update records in the data source</param>
/// <param name="dataSet">The DataSet used to update the data source</param>
/// <param name="tableName">The DataTable used to update the data source.</param>
public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
{
if (insertCommand == null) throw new ArgumentNullException("insertCommand");
if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
if (updateCommand == null) throw new ArgumentNullException("updateCommand");
if (tableName == null || tableName.Length == ) throw new ArgumentNullException("tableName"); // Create a SqlDataAdapter, and dispose of it after we are done
using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
{
// Set the data adapter commands
dataAdapter.UpdateCommand = updateCommand;
dataAdapter.InsertCommand = insertCommand;
dataAdapter.DeleteCommand = deleteCommand; // Update the dataset changes in the data source
dataAdapter.Update(dataSet, tableName); // Commit all the changes made to the DataSet
dataSet.AcceptChanges();
}
}
#endregion #region CreateCommand
/// <summary>
/// Simplify the creation of a Sql command object by allowing
/// a stored procedure and optional parameters to be provided
/// </summary>
/// <remarks>
/// e.g.:
/// SqlCommand command = CreateCommand(conn, "AddCustomer", "CustomerID", "CustomerName");
/// </remarks>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="sourceColumns">An array of string to be assigned as the source columns of the stored procedure parameters</param>
/// <returns>A valid SqlCommand object</returns>
public static SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // Create a SqlCommand
SqlCommand cmd = new SqlCommand(spName, connection);
cmd.CommandType = CommandType.StoredProcedure; // If we receive parameter values, we need to figure out where they go
if ((sourceColumns != null) && (sourceColumns.Length > ))
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Assign the provided source columns to these parameters based on parameter order
for (int index = ; index < sourceColumns.Length; index++)
commandParameters[index].SourceColumn = sourceColumns[index]; // Attach the discovered parameters to the SqlCommand object
AttachParameters(cmd, commandParameters);
} return cmd;
}
#endregion #region ExecuteNonQueryTypedParams
/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
/// the connection string using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
/// SqlTransaction using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
/// </summary>
/// <param name="transaction">A valid SqlTransaction object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An int representing the number of rows affected by the command</returns>
public static int ExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // Sf the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion #region ExecuteDatasetTypedParams
/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); //If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the dataRow column values as the store procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
/// </summary>
/// <param name="transaction">A valid SqlTransaction object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
} #endregion #region ExecuteReaderTypedParams
/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="transaction">A valid SqlTransaction object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>A SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion #region ExecuteScalarTypedParams
/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
/// the connection string using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalarTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="transaction">A valid SqlTransaction object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion #region ExecuteXmlReaderTypedParams
/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
} /// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the dataRow column values as the stored procedure's parameters values.
/// This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <param name="transaction">A valid SqlTransaction object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); // If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > )
{
// Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // Set the parameters values
AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion } /// <summary>
/// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
/// ability to discover parameters for stored procedures at run-time.
/// </summary>
public sealed class SqlHelperParameterCache
{
#region private methods, variables, and constructors //Since this class provides only static methods, 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 appropriate set of SqlParameters for a stored procedure
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="includeReturnValueParameter">Whether or not to include their return value parameter</param>
/// <returns>The parameter array discovered.</returns>
private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); SqlCommand cmd = new SqlCommand(spName, connection);
cmd.CommandType = CommandType.StoredProcedure; connection.Open();
SqlCommandBuilder.DeriveParameters(cmd);
connection.Close(); if (!includeReturnValueParameter)
{
cmd.Parameters.RemoveAt();
} SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count]; cmd.Parameters.CopyTo(discoveredParameters, ); // Init the parameters with a DBNull value
foreach (SqlParameter discoveredParameter in discoveredParameters)
{
discoveredParameter.Value = DBNull.Value;
}
return discoveredParameters;
} /// <summary>
/// Deep copy of cached SqlParameter array
/// </summary>
/// <param name="originalParameters"></param>
/// <returns></returns>
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length]; for (int i = , 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>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters to be cached</param>
public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; paramCache[hashKey] = commandParameters;
} /// <summary>
/// Retrieve a parameter array from the cache
/// </summary>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <returns>An array of SqlParamters</returns>
public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
if (cachedParameters == null)
{
return null;
}
else
{
return CloneParameters(cachedParameters);
}
} #endregion caching functions #region Parameter Discovery Functions /// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <returns>An array of SqlParameters</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
{
return GetSpParameterSet(connectionString, spName, false);
} /// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="connectionString">A valid connection string for a SqlConnection</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
/// <returns>An array of SqlParameters</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
if (connectionString == null || connectionString.Length == ) throw new ArgumentNullException("connectionString");
if (spName == null || spName.Length == ) throw new ArgumentNullException("spName"); using (SqlConnection connection = new SqlConnection(connectionString))
{
return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
}
} /// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <returns>An array of SqlParameters</returns>
internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
{
return GetSpParameterSet(connection, spName, false);
} /// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
/// <returns>An array of SqlParameters</returns>
internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
if (connection == null) throw new ArgumentNullException("connection");
using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone())
{
return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
}
} /// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <param name="connection">A valid SqlConnection object</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
/// <returns>An array of SqlParameters</returns>
private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
if (connection == null) throw new ArgumentNullException("connection");
if (spName == null || spName.Length == ) 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;
} return CloneParameters(cachedParameters);
} #endregion Parameter Discovery Functions } }

三,SqlHelper类扩展,及Access支持:

 using System.Data.Common;

 namespace Classbao.Data
{
public sealed partial class SqlHelper
{ #region perfect SqlHelper
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("command");
if (commandText == null || commandText.Length == ) throw new ArgumentNullException("commandText"); command.Connection = connection;
command.CommandText = commandText;
command.CommandType = commandType;
if (transaction != null)
{
if (transaction.Connection == null)
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
command.Transaction = transaction;
command.Connection = transaction.Connection;
}
AttachParameters(command, commandParameters);
} public static object ExecuteScalar(SqlCommand command, CommandType commandType, string commandText)
{
return ExecuteReader(command, commandType, commandText, (SqlParameter[])null);
} public static object ExecuteScalar(SqlCommand command, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("SqlCommand");
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, command.Connection, command.Transaction, commandType, commandText, commandParameters);
object result = DataAccessHelper.ExecuteScalar(cmd);
cmd.Parameters.Clear();
return result;
} public static SqlDataReader ExecuteReader(SqlCommand command, CommandType commandType, string commandText)
{
return ExecuteReader(command, commandType, commandText, (SqlParameter[])null);
}
public static SqlDataReader ExecuteReader(SqlCommand command, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("SqlCommand");
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, command.Connection, command.Transaction, commandType, commandText, commandParameters);
SqlDataReader result = (SqlDataReader)DataAccessHelper.ExecuteReader(cmd);
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
if (commandParameter.Direction != ParameterDirection.Input)
{
canClear = false;
break;
} if (canClear)
cmd.Parameters.Clear();
return result;
}
public static int ExecuteNonQuery(SqlCommand command, CommandType commandType, string commandText)
{
return ExecuteNonQuery(command, commandType, commandText, (SqlParameter[])null);
}
public static int ExecuteNonQuery(SqlCommand command, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("SqlCommand");
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = command.CommandTimeout;
PrepareCommand(cmd, command.Connection, command.Transaction, commandType, commandText, commandParameters);
int retval = DataAccessHelper.ExecuteNonQuery(cmd);
cmd.Parameters.Clear();
return retval;
} public static DataSet ExecuteDataset(SqlCommand command, CommandType commandType, string commandText)
{
// Pass through the call providing null for the set of SqlParameters
return ExecuteDataset(command, commandType, commandText, (SqlParameter[])null);
} public static DataSet ExecuteDataset(SqlCommand command, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (command == null) throw new ArgumentNullException("SqlCommand"); // Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = ;
PrepareCommand(cmd, command.Connection, command.Transaction, commandType, commandText, commandParameters);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet result = new DataSet();
DataAccessHelper.Fill(da, result);
cmd.Parameters.Clear();
return result;
} } #endregion #region DataAccessHelper
class DataAccessHelper
{ static void ExceptionHandler(SystemException e)
{
throw (new Exception(e.Message, e));
}
public static int ExecuteNonQuery(DbCommand command)
{ bool isNeedClose = OpenConnection(command.Connection);
try
{
return command.ExecuteNonQuery();
}
catch (SystemException e)
{
ExceptionHandler(e);
return ;
}
finally
{
if (isNeedClose)
CloseConnection(command.Connection);
}
}
public static object ExecuteScalar(DbCommand command)
{
bool isNeedClose = OpenConnection(command.Connection);
try
{
return command.ExecuteScalar();
}
catch (SystemException e)
{
ExceptionHandler(e);
return null;
}
finally
{
if (isNeedClose)
CloseConnection(command.Connection);
}
}
public static void Fill(DbDataAdapter dataAdapter, DataSet set)
{
dataAdapter.Fill(set);
}
public static DbDataReader ExecuteReader(DbCommand command)
{ bool isNeedClose = OpenConnection(command.Connection);
DbDataReader result = null;
try
{
if (isNeedClose)
result = command.ExecuteReader(CommandBehavior.CloseConnection);
else
result = command.ExecuteReader();
}
catch (SystemException e)
{
ExceptionHandler(e);
if (isNeedClose)
CloseConnection(command.Connection);
}
return result;
}
public static bool OpenConnection(DbConnection connection)
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
return true;
}
return false;
}
public static bool CloseConnection(DbConnection connection)
{
bool result = connection.State == ConnectionState.Open;
connection.Close();
return result;
} } #endregion
}
}

微软版的SqlHelper.cs类的更多相关文章

  1. 微软SQLHelper.cs类 中文版

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Co ...

  2. 微软SQLHelper.cs类

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  3. 处女篇:自用C#后端SqlHelper.cs类

    自用SqlHelper.cs类,此类来自软谋教育徐老师课程SqlHelper.cs! using System; using System.Collections; using System.Coll ...

  4. 微软C#版SQLHelper.cs类

    转载自:http://blog.csdn.net/fengqingtao2008/article/details/17399247 using System; using System.Data; u ...

  5. SQLHelper.cs类 微软C#版

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  6. C#版SQLHelper.cs类

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  7. WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据

    WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据 WebForm1.aspx 页面 (原生AJAX请求,写法一) <%@ Page Langu ...

  8. WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据(转)

    WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据 WebForm1.aspx 页面 (原生AJAX请求,写法一) <%@ Page Langu ...

  9. 存储过程及Comm.cs类的创建

    2013-09-25 13:08:59 一.准备工作 首先创建一个数据库,如创建“试用期公务员管理”数据库:再创建一个Comm.cs类,添加代码如下: using System;using Syste ...

随机推荐

  1. AnguarJS 第一天----Hello World

    AngularJS是什么? AngularJS是目前很火的前端JS框架之一, AngularJS的开发团队将其描述为一种构建动态Web应用的结构化框架.它是完全使用JavaScript编写的客户端技术 ...

  2. 【Java并发编程实战】-----synchronized

    在我们的实际应用当中可能经常会遇到这样一个场景:多个线程读或者.写相同的数据,访问相同的文件等等.对于这种情况如果我们不加以控制,是非常容易导致错误的.在java中,为了解决这个问题,引入临界区概念. ...

  3. madplay播放控制

    管理madplay的主程序,包括播放,暂停播放,恢复播放,停止播放system("madplay north.mp3 &");//利用system函数调用madplay播放 ...

  4. ASP.NET Web API的Controller是如何被创建的?

    Web API调用请求的目标是定义在某个HttpController类型中的某个Action方法,所以消息处理管道最终需要激活目标HttpController对象.调用请求的URI会携带目标HttpC ...

  5. Session中放错误提示JSP上获取

    servlet中: message= "图片上传失败!"; request.setAttribute("message",message);   JSP中运用一 ...

  6. 我也来说说DDD~大话目录

    回到占占推荐博客索引 DDD之前没有接触过,但一但有了接触就一发不可收拾,他会带去进入一个全新的世界! DDD不是新技术,而是新思想,新模式,是软件开发领域的一次突破,它更接近于业务,对于业务的改动它 ...

  7. CocoaPods pod 安装、更新慢解决方法

    使用CocoaPods来添加第三方类库,无论是执行pod install还是pod update都卡在了Analyzing dependencies不动了,令人甚是DT. 每一次都忘记现在自己记录一下 ...

  8. 改变textView的个别字体颜色

    Spannable span = new SpannableString(getString(R.string.register_need_to_ageree));//例如:register_need ...

  9. Referenced file contains errors (http://www.springframework.org/schema/context). For more information, right click on the message in the Problems

    spring 配置文件的DTD或schema出问题,一般两种情况: 1.当前网络环境不稳定,按住ctrl+"http://www.springframework.org/schema/con ...

  10. SSIS Destination 组件使用Fast-Load mode出错

    查看一个Package的历史Message 数据,发现 DataFlow Task 经常出错,错误信息的Description是: Description: "While reading c ...