using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
namespace SqlServerDAL
{
public sealed class SqlHelper
{
public static readonly string conn = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
public static SqlTransaction getTran()
{
SqlConnection cn = new SqlConnection(SqlHelper.conn);
SqlTransaction tran = null;
cn.Open();
tran = cn.BeginTransaction();
return tran;
}
#region private utility methods & constructors
/// <summary>
/// 将命令和一组参数对象联系起来,给输出类型参数对象赋空值
/// </summary>
/// <param name="command">命令对象</param>
/// <param name="commandParameters">参数数组</param>
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
foreach (SqlParameter par in commandParameters)
{
if ((par.Direction == ParameterDirection.InputOutput) && (par.Value == null))
{
par.Value = DBNull.Value;
}
command.Parameters.Add(par);
}
}
/// <summary>
/// 对一组参数对象赋值
/// </summary>
/// <param name="commandParameters">参数对象</param>
/// <param name="parameterValues">参数值</param>
public static void AssignParameterValues(SqlParameter[] commandParameters, params object[] parameterValues)
{
if ((parameterValues == null) || (parameterValues == null))
{
return;
}
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("parameter count does not match parameter value count..");
}
for (int i = 0, j = commandParameters.Length; i < j; i++)
{
if (parameterValues[i] != null && (commandParameters[i].Direction == ParameterDirection.Input || commandParameters[i].Direction == ParameterDirection.InputOutput))
{
commandParameters[i].Value = parameterValues[i];
}
}
}
/// <summary>
/// 对一组参数对象赋值
/// </summary>
/// <param name="commandParameters"></param>
/// <param name="parameterValues"></param>
public static void AssignParameterValues(SqlParameter[] commandParameters, Hashtable parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
return;
}
if (commandParameters.Length != parameterValues.Count)
{
throw new ArgumentException("parameter count does not mathc prameter value coount.");
} for (int i = 0, j = parameterValues.Count; i < j; i++)
{
if (parameterValues[commandParameters[i].ParameterName] != null && (commandParameters[i].Direction == ParameterDirection.Input || commandParameters[i].Direction == ParameterDirection.InputOutput))
{
commandParameters[i].Value = parameterValues[commandParameters[i].ParameterName];
}
}
}
/// <summary>
/// 将一组COMMAND相关对象关联
/// </summary>
/// <param name="command"></param>
/// <param name="connection"></param>
/// <param name="transaction"></param>
/// <param name="commandType"></param>
/// <param name="commandText"></param>
/// <param name="commandParameters"></param>
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
command.CommandType = commandType;
command.CommandText = commandText;
command.Connection = connection;
if (transaction != null)
{
command.Transaction = transaction;
}
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
}
#endregion
#region ExecuteNonQuery
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
{
return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
}
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
}
}
public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
SqlHelper.AssignParameterValues(commandParameters, parameterValues);
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
}
public static int ExecuteNonQuery(string connectionString, string spName, Hashtable parameterValues)
{
if ((parameterValues != null) && (parameterValues.Count > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
}
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
}
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
int retVal = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return retVal;
}
public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
}
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
}
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
int retVal = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return retVal;
}
public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteDataSet
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
{
return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
}
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
return ExecuteDataset(cn, commandType, commandText, commandParameters);
}
}
public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
}
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
}
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
}
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
}
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteReader
private enum sqlConnectionOwnership
{
Internal,
External
}
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, sqlConnectionOwnership connectionOwnership)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
SqlDataReader dr;
if (connectionOwnership == sqlConnectionOwnership.External)
{
dr = cmd.ExecuteReader();
}
else
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
cmd.Parameters.Clear();
return dr;
}
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
{
return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
}
public static SqlDataReader ExecuteReader(string connectionstring, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlConnection cn = new SqlConnection(connectionstring);
cn.Open();
try
{
return ExecuteReader(cn, null, commandType, commandText, commandParameters, sqlConnectionOwnership.Internal);
}
catch
{
cn.Close();
throw;
}
}
public static SqlDataReader ExecuteReader(string connectionstring, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionstring, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteReader(connectionstring, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteReader(connectionstring, CommandType.StoredProcedure, spName);
}
}
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
}
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, sqlConnectionOwnership.External);
}
public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
}
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
}
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, sqlConnectionOwnership.External);
}
public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
#region ExecuteScalar
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
{
return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
}
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
return ExecuteScalar(cn, commandType, commandText, commandParameters);
}
}
public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
}
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
{
return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
}
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
object retValue = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return retValue;
}
public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
}
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
{
return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
}
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
object retVal = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return retVal;
}
public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
else
{
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
}
#endregion
}
public sealed class SqlHelperParameterCache
{
#region private methods,variables,and conestructors
//类提供的都是静态方法,将默认构造函数设置为私有的以便阻止利用"new SqlHelperParameterCache()"来实例化类
private SqlHelperParameterCache() { }
//存储过程参数缓存导HashTable中
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="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="connectionString">一个连接对象的有效连接串</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="spName">存储过程名</param>
/// <param name="includeReturnValueParameter">是否有返回值参数</param>
/// <returns>参数对象数组,存储过程的所有参数信息</returns>
private static SqlParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(spName, cn))
{
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
//从sqlcommand指定的存储过程中检索信息,并填充指定的sqlcommand对象的Parameters集合中。
SqlCommandBuilder.DeriveParameters(cmd);
if (!includeReturnValueParameter)
{
//移除第一个参数对象,因为没有返回值,而默认情况下,第一个参数对象是返回值
cmd.Parameters.RemoveAt(0);
}
SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];
cmd.Parameters.CopyTo(discoveredParameters, 0);
return discoveredParameters;
}
}
}
//复制缓存参数数据(克隆)
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];
for (int i = 0; i < originalParameters.Length; i++)
{
clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
}
return clonedParameters;
}
#endregion
#region caching functions
/// <summary>
///将参数数组添加到缓存中
/// </summary>
/// <param name="connectionString">有效的连接串</param>
/// <param name="commandText">一个存储过名程名或者T-SQL命令</param>
/// <param name="commandParameters">一个要被缓存的参数数组</param>
public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
{
string hashKey = connectionString + ":" + commandText;
paramCache[hashKey] = commandParameters;
}
/// <summary>
/// 从缓存中获得参数对象数组
/// </summary>
/// <param name="connectionString">有效的连接串</param>
/// <param name="commandText">一个存储过程名或者T-SQL命令</param>
/// <returns>一个参数对象数组</returns>
public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
{
string hashKey = connectionString + ":" + commandText;
SqlParameter[] cacheParameters = (SqlParameter[])paramCache[hashKey];
if (cacheParameters == null)
{
//如果缓存中没有参数,返回空
return null;
}
else
{
//返回参数的副本
return CloneParameters(cacheParameters);
}
}
#endregion
#region Parameter Discovery Functions
/// <summary>
/// 获得存储过程的参数集
/// </summary>
/// <remarks >
/// 这个方法从数据库中获得信息,并将之存储在缓存,以便以后使用
/// </remarks>
/// <param name="connectionString">有效的连接串</param>
/// <param name="spName">一个存储过程名或者T-SQL命令</param>
/// <returns>一个参数对象数组</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
{
return GetSpParameterSet(connectionString, spName, false);
}
/// <summary>
/// 获得存储过程的参数集
/// </summary>
/// <remarks>
/// 这个方法从数据库中获得信息,并将之存储在缓存,以便之后的使用
/// </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>
/// <param name="connectionString">有效的连接串</param>
/// <param name="commandText">一个存储过程名</param>
/// /// <param name="includeReturnValueParameter">是否有返回值参数</param>
/// <returns>一个参数对象数组</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
string hashKey = connectionString + ":" + spName + (includeReturnValueParameter ? ": include ReturnValue Parameter" : "");
SqlParameter[] cachedParameters;
cachedParameters = (SqlParameter[])paramCache[hashKey];
if (cachedParameters == null)
{
cachedParameters = (SqlParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(connectionString, spName, includeReturnValueParameter));
}
return CloneParameters(cachedParameters);
}
#endregion
}
}