SqlHelper(一)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.SqlClient;
/// <summary>
/// 数据库的通用访问代码
/// 此类为抽象类,不允许实例化,在应用时直接调用即可
/// </summary>
public abstract class SqlHelper
{
//获取数据库连接字符串,其属于静态变量且只读,项目中所有文档可以直接使用,但不能修改
public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;
// 哈希表用来存储缓存的参数信息,哈希表可以存储任意类型的参数。
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
/// <summary>
///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
/// 使用参数数组形式提供参数列表
/// </summary>
/// <remarks>
/// 使用示例:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
//通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
//清空SqlCommand中的参数列表
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
///执行一条不返回结果的SqlCommand,通过一个已经存在的数据库连接
/// 使用参数数组提供参数
/// </summary>
/// <remarks>
/// 使用示例:
/// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">一个现有的数据库连接</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事务处理
/// 使用参数数组提供参数
/// </summary>
/// <remarks>
/// 使用示例:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="trans">一个存在的 sql 事务处理</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行一条返回结果集的SqlCommand命令,通过专用的连接字符串。
/// 使用参数数组提供参数
/// </summary>
/// <remarks>
/// 使用示例:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个包含结果的SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
// 在这里使用try/catch处理是因为如果方法出现异常,则SqlDataReader就不存在,
//CommandBehavior.CloseConnection的语句就不会执行,触发的异常由catch捕获。
//关闭数据库连接,并通过throw再次引发捕捉到的异常。
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
/// <summary>
/// 执行一条返回第一条记录第一列的SqlCommand命令,通过专用的连接字符串。
/// 使用参数数组提供参数
/// </summary>
/// <remarks>
/// 使用示例:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个object类型的数据,可以通过 Convert.To{Type}方法转换类型</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// 执行一条返回第一条记录第一列的SqlCommand命令,通过已经存在的数据库连接。
/// 使用参数数组提供参数
/// </summary>
/// <remarks>
/// 使用示例:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">一个已经存在的数据库连接</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个object类型的数据,可以通过 Convert.To{Type}方法转换类型</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 缓存参数数组
/// </summary>
/// <param name="cacheKey">参数缓存的键值</param>
/// <param name="cmdParms">被缓存的参数列表</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
/// <summary>
/// 获取被缓存的参数
/// </summary>
/// <param name="cacheKey">用于查找参数的KEY值</param>
/// <returns>返回缓存的参数数组</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
//新建一个参数的克隆列表
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
//通过循环为克隆参数列表赋值
for (int i = 0, j = cachedParms.Length; i < j; i++)
//使用clone方法复制参数列表中的参数
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
/// <summary>
/// 为执行命令准备参数
/// </summary>
/// <param name="cmd">SqlCommand 命令</param>
/// <param name="conn">已经存在的数据库连接</param>
/// <param name="trans">数据库事务处理</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param>
/// <param name="cmdParms">返回带参数的命令</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
//判断数据库连接状态
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
//判断是否需要事务处理
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
cmd.Parameters.AddRange(cmdParms);
}
}
}
SqlHelper(二)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace DotNet.Utilities
{
/// <summary>
/// 数据库的通用访问代码
/// 此类为抽象类,不允许实例化,在应用时直接调用即可
/// </summary>
public abstract class SqlHelper
{
/// <summary>
/// 数据库连接字符串
/// </summary>
public static readonly string connectionString = System.Configuration.ConfigurationSettings.AppSettings["con"].ToString().Trim();
// Hashtable to store cached parameters
private static Hashtable _parmCache = Hashtable.Synchronized(new Hashtable());
#region ExecteNonQuery方法
/// <summary>
/// 执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
/// 使用参数数组形式提供参数列表
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
//通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
//清空SqlCommand中的参数列表
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
/// 使用参数数组形式提供参数列表
/// </summary>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecteNonQuery(connectionString, cmdType, cmdText, commandParameters);
}
/// <summary>
///存储过程专用
/// </summary>
/// <param name="cmdText">存储过程的名字</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecteNonQueryProducts(string cmdText, params SqlParameter[] commandParameters)
{
return ExecteNonQuery(CommandType.StoredProcedure, cmdText, commandParameters);
}
/// <summary>
///Sql语句专用
/// </summary>
/// <param name="cmdText">T_Sql语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecteNonQueryText(string cmdText, params SqlParameter[] commandParameters)
{
return ExecteNonQuery(CommandType.Text, cmdText, commandParameters);
}
#endregion
#region GetTable方法
/// <summary>
/// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
/// 使用参数数组提供参数
/// </summary>
/// <param name="connecttionString">一个现有的数据库连接</param>
/// <param name="cmdTye">SqlCommand命令类型</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
public static DataTableCollection GetTable(string connecttionString, CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connecttionString))
{
PrepareCommand(cmd, conn, null, cmdTye, cmdText, commandParameters);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
}
return ds.Tables;
}
/// <summary>
/// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
/// 使用参数数组提供参数
/// </summary>
/// <param name="cmdTye">SqlCommand命令类型</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
public static DataTableCollection GetTable(CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
{
return GetTable(connectionString, cmdTye, cmdText, commandParameters);
}
/// <summary>
/// 存储过程专用
/// </summary>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
public static DataTableCollection GetTableProducts(string cmdText, SqlParameter[] commandParameters)
{
return GetTable(CommandType.StoredProcedure, cmdText, commandParameters);
}
/// <summary>
/// Sql语句专用
/// </summary>
/// <param name="cmdText"> T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
public static DataTableCollection GetTableText(string cmdText, SqlParameter[] commandParameters)
{
return GetTable(CommandType.Text, cmdText, commandParameters);
}
#endregion
/// <summary>
/// 为执行命令准备参数
/// </summary>
/// <param name="cmd">SqlCommand 命令</param>
/// <param name="conn">已经存在的数据库连接</param>
/// <param name="trans">数据库事物处理</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param>
/// <param name="cmdParms">返回带参数的命令</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
//判断数据库连接状态
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
//判断是否需要事物处理
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
cmd.Parameters.AddRange(cmdParms);
}
}
/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>A SqlDataReader containing the results</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
#region ExecuteDataSet方法
/// <summary>
/// return a dataset
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>return a dataset</returns>
public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
}
}
catch
{
throw;
}
}
/// <summary>
/// 返回一个DataSet
/// </summary>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>return a dataset</returns>
public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(connectionString, cmdType, cmdText, commandParameters);
}
/// <summary>
/// 返回一个DataSet
/// </summary>
/// <param name="cmdText">存储过程的名字</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>return a dataset</returns>
public static DataSet ExecuteDataSetProducts(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
}
/// <summary>
/// 返回一个DataSet
/// </summary>
/// <param name="cmdText">T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>return a dataset</returns>
public static DataSet ExecuteDataSetText(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteDataSet(connectionString, CommandType.Text, cmdText, commandParameters);
}
public static DataView ExecuteDataSet(string connectionString, string sortExpression, string direction, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = sortExpression + " " + direction;
return dv;
}
}
catch
{
throw;
}
}
#endregion
#region // ExecuteScalar方法
/// <summary>
/// 返回第一行的第一列
/// </summary>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个对象</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(SqlHelper.connectionString, cmdType, cmdText, commandParameters);
}
/// <summary>
/// 返回第一行的第一列存储过程专用
/// </summary>
/// <param name="cmdText">存储过程的名字</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个对象</returns>
public static object ExecuteScalarProducts(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(SqlHelper.connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
}
/// <summary>
/// 返回第一行的第一列Sql语句专用
/// </summary>
/// <param name="cmdText">者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个对象</returns>
public static object ExecuteScalarText(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(SqlHelper.connectionString, CommandType.Text, cmdText, commandParameters);
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
#endregion
/// <summary>
/// add parameter array to the cache
/// </summary>
/// <param name="cacheKey">Key to the parameter cache</param>
/// <param name="cmdParms">an array of SqlParamters to be cached</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
_parmCache[cacheKey] = commandParameters;
}
/// <summary>
/// Retrieve cached parameters
/// </summary>
/// <param name="cacheKey">key used to lookup parameters</param>
/// <returns>Cached SqlParamters array</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])_parmCache[cacheKey];
if (cachedParms == null)
return null;
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
cachedParms.CopyTo(clonedParms, 0);
return clonedParms;
}
/// <summary>
/// 检查是否存在
/// </summary>
/// <param name="strSql">Sql语句</param>
/// <param name="cmdParms">参数</param>
/// <returns>bool结果</returns>
public static bool Exists(string strSql, params SqlParameter[] cmdParms)
{
int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, cmdParms));
return cmdresult != 0;
}
}
}
SqlHelper(三)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace DotNet
{
public class SQLHelper
{
// 超时时间
private static int Timeout = 1000;
// 数据库名称
public const String BestNet = "BestNet";
// 存储过程名称
public const String UserInfoCURD = "UserInfoCURD";
// 数据库连接字符串
private static Dictionary<String, String> ConnStrs = new Dictionary<String, String>();
/// <summary>
/// SQLServer操作类(静态构造函数)
/// </summary>
static SQLHelper()
{
ConnectionStringSettingsCollection configs = WebConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings config in configs)
{
ConnStrs.Add(config.Name, config.ConnectionString);
}
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <param name="database">数据库(配置文件内connectionStrings的name)</param>
/// <returns>数据库连接</returns>
private static SqlConnection GetConnection(string database)
{
if (string.IsNullOrEmpty(database))
{
throw new Exception("未设置参数:database");
}
if (!ConnStrs.ContainsKey(database))
{
throw new Exception("未找到数据库:" + database);
}
return new SqlConnection(ConnStrs[database]);
}
/// <summary>
/// 获取SqlCommand
/// </summary>
/// <param name="conn">SqlConnection</param>
/// <param name="transaction">SqlTransaction</param>
/// <param name="cmdType">CommandType</param>
/// <param name="sql">SQL</param>
/// <param name="parms">SqlParameter数组</param>
/// <returns></returns>
private static SqlCommand GetCommand(SqlConnection conn, SqlTransaction transaction, CommandType cmdType, string sql, SqlParameter[] parms)
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = cmdType;
cmd.CommandTimeout = Timeout;
if (transaction != null)
cmd.Transaction = transaction;
if (parms != null && parms.Length != 0)
cmd.Parameters.AddRange(parms);
return cmd;
}
/// <summary>
/// 查询数据,返回DataTable
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="parms">参数</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <returns>DataTable</returns>
public static DataTable QueryDataTable(string database, string sql, SqlParameter[] parms, CommandType cmdType)
{
if (string.IsNullOrEmpty(database))
{
throw new Exception("未设置参数:database");
}
if (string.IsNullOrEmpty(sql))
{
throw new Exception("未设置参数:sql");
}
try
{
using (SqlConnection conn = GetConnection(database))
{
conn.Open();
using (SqlCommand cmd = GetCommand(conn, null, cmdType, sql, parms))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}
catch (SqlException ex)
{
System.Text.StringBuilder log = new System.Text.StringBuilder();
log.Append("查询数据出错:");
log.Append(ex);
throw new Exception(log.ToString());
}
}
/// <summary>
/// 查询数据,返回DataSet
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="parms">参数</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <returns>DataSet</returns>
public static DataSet QueryDataSet(string database, string sql, SqlParameter[] parms, CommandType cmdType)
{
if (string.IsNullOrEmpty(database))
{
throw new Exception("未设置参数:database");
}
if (string.IsNullOrEmpty(sql))
{
throw new Exception("未设置参数:sql");
}
try
{
using (SqlConnection conn = GetConnection(database))
{
conn.Open();
using (SqlCommand cmd = GetCommand(conn, null, cmdType, sql, parms))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
}
catch (SqlException ex)
{
System.Text.StringBuilder log = new System.Text.StringBuilder();
log.Append("查询数据出错:");
log.Append(ex);
throw new Exception(log.ToString());
}
}
/// <summary>
/// 执行命令获取唯一值(第一行第一列)
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="parms">参数</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <returns>获取值</returns>
public static object QueryScalar(string database, string sql, SqlParameter[] parms, CommandType cmdType)
{
if (string.IsNullOrEmpty(database))
{
throw new Exception("未设置参数:database");
}
if (string.IsNullOrEmpty(sql))
{
throw new Exception("未设置参数:sql");
}
try
{
using (SqlConnection conn = GetConnection(database))
{
conn.Open();
using (SqlCommand cmd = GetCommand(conn, null, cmdType, sql, parms))
{
return cmd.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
System.Text.StringBuilder log = new System.Text.StringBuilder();
log.Append("处理出错:");
log.Append(ex);
throw new Exception(log.ToString());
}
}
/// <summary>
/// 执行命令更新数据
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="parms">参数</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <returns>更新的行数</returns>
public static int Execute(string database, string sql, SqlParameter[] parms, CommandType cmdType)
{
if (string.IsNullOrEmpty(database))
{
throw new Exception("未设置参数:database");
}
if (string.IsNullOrEmpty(sql))
{
throw new Exception("未设置参数:sql");
}
//返回(增删改)的更新行数
int count = 0;
try
{
using (SqlConnection conn = GetConnection(database))
{
conn.Open();
using (SqlCommand cmd = GetCommand(conn, null, cmdType, sql, parms))
{
if (cmdType == CommandType.StoredProcedure)
cmd.Parameters.AddWithValue("@RETURN_VALUE", "").Direction = ParameterDirection.ReturnValue;
count = cmd.ExecuteNonQuery();
if (count <= 0)
if (cmdType == CommandType.StoredProcedure)
count = (int)cmd.Parameters["@RETURN_VALUE"].Value;
}
}
}
catch (SqlException ex)
{
System.Text.StringBuilder log = new System.Text.StringBuilder();
log.Append("处理出错:");
log.Append(ex);
throw new Exception(log.ToString());
}
return count;
}
/// <summary>
/// 查询数据,返回DataTable
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <param name="values">参数</param>
/// <returns>DataTable</returns>
public static DataTable QueryDataTable(string database, string sql, CommandType cmdType, IDictionary<string, object> values)
{
SqlParameter[] parms = DicToParams(values);
return QueryDataTable(database, sql, parms, cmdType);
}
/// <summary>
/// 执行存储过程查询数据,返回DataSet
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <param name="values">参数
/// <returns>DataSet</returns>
public static DataSet QueryDataSet(string database, string sql, CommandType cmdType, IDictionary<string, object> values)
{
SqlParameter[] parms = DicToParams(values);
return QueryDataSet(database, sql, parms, cmdType);
}
/// <summary>
/// 执行命令获取唯一值(第一行第一列)
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <param name="values">参数</param>
/// <returns>唯一值</returns>
public static object QueryScalar(string database, string sql, CommandType cmdType, IDictionary<string, object> values)
{
SqlParameter[] parms = DicToParams(values);
return QueryScalar(database, sql, parms, cmdType);
}
/// <summary>
/// 执行命令更新数据
/// </summary>
/// <param name="database">数据库</param>
/// <param name="sql">SQL语句或存储过程名</param>
/// <param name="cmdType">查询类型(SQL语句/存储过程名)</param>
/// <param name="values">参数</param>
/// <returns>更新的行数</returns>
public static int Execute(string database, string sql, CommandType cmdType, IDictionary<string, object> values)
{
SqlParameter[] parms = DicToParams(values);
return Execute(database, sql, parms, cmdType);
}
/// <summary>
/// 创建参数
/// </summary>
/// <param name="name">参数名</param>
/// <param name="type">参数类型</param>
/// <param name="size">参数大小</param>
/// <param name="direction">参数方向(输入/输出)</param>
/// <param name="value">参数值</param>
/// <returns>新参数对象</returns>
public static SqlParameter[] DicToParams(IDictionary<string, object> values)
{
if (values == null) return null;
SqlParameter[] parms = new SqlParameter[values.Count];
int index = 0;
foreach (KeyValuePair<string, object> kv in values)
{
SqlParameter parm = null;
if (kv.Value == null)
{
parm = new SqlParameter(kv.Key, DBNull.Value);
}
else
{
Type t = kv.Value.GetType();
parm = new SqlParameter(kv.Key, NetToSql(kv.Value.GetType()));
parm.Value = kv.Value;
}
parms[index++] = parm;
}
return parms;
}
/// <summary>
/// .net类型转换为Sql类型
/// </summary>
/// <param name="t">.net类型</param>
/// <returns>Sql类型</returns>
public static SqlDbType NetToSql(Type t)
{
SqlDbType dbType = SqlDbType.Variant;
switch (t.Name)
{
case "Int16":
dbType = SqlDbType.SmallInt;
break;
case "Int32":
dbType = SqlDbType.Int;
break;
case "Int64":
dbType = SqlDbType.BigInt;
break;
case "Single":
dbType = SqlDbType.Real;
break;
case "Decimal":
dbType = SqlDbType.Decimal;
break;
case "Byte[]":
dbType = SqlDbType.VarBinary;
break;
case "Boolean":
dbType = SqlDbType.Bit;
break;
case "String":
dbType = SqlDbType.NVarChar;
break;
case "Char[]":
dbType = SqlDbType.Char;
break;
case "DateTime":
dbType = SqlDbType.DateTime;
break;
case "DateTime2":
dbType = SqlDbType.DateTime2;
break;
case "DateTimeOffset":
dbType = SqlDbType.DateTimeOffset;
break;
case "TimeSpan":
dbType = SqlDbType.Time;
break;
case "Guid":
dbType = SqlDbType.UniqueIdentifier;
break;
case "Xml":
dbType = SqlDbType.Xml;
break;
case "Object":
dbType = SqlDbType.Variant;
break;
}
return dbType;
}
}
}