using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Configuration; namespace WebSqlHelper { /// /// 数据库的通用访问代码 /// 此类为抽象类,不允许实例化,在应用时直接调用即可 /// public abstract class SqlHelper { //获取数据库连接字符串,其属于静态变量且只读,项目中所有文档可以直接使用,但不能修改 public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["DongShengDB"].ConnectionString; //public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString2"].ConnectionString; //public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString; //public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["SQLProfileConnString"].ConnectionString; // public static readonly string ConnectionStringPrint = ConfigurationManager.ConnectionStrings["DongShengPR"].ConnectionString; // 哈希表用来存储缓存的参数信息,哈希表可以存储任意类型的参数。 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); private static SqlConnection _sqlConnection; /// ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。 /// 使用参数数组形式提供参数列表 /// /// /// 使用示例: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个有效的数据库连接字符串 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中 PrepareCommand(cmd, conn, null, cmdType, cmdText); int val = cmd.ExecuteNonQuery(); return val; } } /// ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。 /// 使用参数数组形式提供参数列表 /// /// /// 使用示例: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个有效的数据库连接字符串 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 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; } } /// ///执行一条不返回结果的SqlCommand,通过一个已经存在的数据库连接 /// 使用参数数组提供参数 /// /// /// 使用示例: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个现有的数据库连接 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 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; } /// /// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事物处理 /// 使用参数数组提供参数 /// /// /// 使用示例: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个存在的 sql 事物处理 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 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; } public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText); int val = cmd.ExecuteNonQuery(); return val; } /// /// 执行一条返回结果集的SqlCommand命令,通过专用的连接字符串。 /// 使用参数数组提供参数 /// /// /// 使用示例: /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个有效的数据库连接字符串 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个包含结果的SqlDataReader 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; } } /// /// 执行一条返回第一条记录第一列的SqlCommand命令,通过专用的连接字符串。 /// 使用参数数组提供参数 /// /// /// 使用示例: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个有效的数据库连接字符串 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个object类型的数据,可以通过 Convert.To{Type}方法转换类型 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; } } /// /// 执行一条返回第一条记录第一列的SqlCommand命令,通过已经存在的数据库连接。 /// 使用参数数组提供参数 /// /// /// 使用示例: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个已经存在的数据库连接 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个object类型的数据,可以通过 Convert.To{Type}方法转换类型 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; } /// /// 执行一条返回第一条记录第一列的SqlCommand命令,通过已经存在的数据库连接。(事务操作) /// 使用参数数组提供参数 /// /// /// 使用示例: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个存在的 sql 事物处理 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 public static object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } /// /// 缓存参数数组 /// /// 参数缓存的键值 /// 被缓存的参数列表 public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// /// 获取被缓存的参数 /// /// 用于查找参数的KEY值 /// 返回缓存的参数数组 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; } /// /// 为执行命令准备参数 /// /// SqlCommand 命令 /// 已经存在的数据库连接 /// 数据库事物处理 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// Command text,T-SQL语句 例如 Select * from Products /// 返回带参数的命令 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText) { //判断数据库连接状态 if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; //判断是否需要事物处理 if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; } /// /// 为执行命令准备参数 /// /// SqlCommand 命令 /// 已经存在的数据库连接 /// 数据库事物处理 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// Command text,T-SQL语句 例如 Select * from Products /// 返回带参数的命令 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) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } /// /// 事务操作 ADD 2011-4-2 JHQ /// /// /// public static SqlTransaction BeginTransaction(string con) { //SqlConnection connection = new SqlConnection(con); _sqlConnection = new SqlConnection(con); _sqlConnection.Open(); SqlTransaction tran = _sqlConnection.BeginTransaction(); return tran; } #region z /// /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in /// the connection string. /// /// /// e.g.: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders"); /// /// A valid connection string for a SqlConnection /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// A dataset containing the resultset generated by the command public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText) { DataSet ds = null; bool mustCloseConnection = false; if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); SqlCommand command = null; using (SqlConnection connection = new SqlConnection(connectionString)) { if (connection.State != ConnectionState.Open) { mustCloseConnection = true; connection.Open(); } else { mustCloseConnection = false; } command = new SqlCommand(); // Associate the connection with the command command.Connection = connection; // Set the command text (stored procedure name or SQL statement) command.CommandText = commandText; using (SqlDataAdapter da = new SqlDataAdapter(command)) { 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 command.Parameters.Clear(); if (mustCloseConnection) connection.Close(); } } return ds; } #endregion #region z /// /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in /// the connection string. /// /// /// e.g.: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders"); /// /// A valid connection string for a SqlConnection /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// A dataset containing the resultset generated by the command public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { DataSet ds = null; bool mustCloseConnection = false; if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); SqlCommand command = null; using (SqlConnection connection = new SqlConnection(connectionString)) { if (connection.State != ConnectionState.Open) { mustCloseConnection = true; connection.Open(); } else { mustCloseConnection = false; } command = new SqlCommand(); // Associate the connection with the command command.Connection = connection; // Set the command text (stored procedure name or SQL statement) command.CommandText = commandText; //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中 PrepareCommand(command, connection, null, commandType, commandText, commandParameters); using (SqlDataAdapter da = new SqlDataAdapter(command)) { 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 command.Parameters.Clear(); if (mustCloseConnection) connection.Close(); } } return ds; } #endregion public static void CloseConnection() { if (_sqlConnection != null) { if (_sqlConnection.State == ConnectionState.Open) { _sqlConnection.Close(); } } } /// /// 执行一条计算查询结果语句,返回查询结果(object)。 /// /// 计算查询结果语句 /// 查询结果(object) public static object GetSingle(string connectionString, string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// /// 执行存储过程 /// /// 存储过程名 /// 存储过程参数 /// DataSet结果中的表名 /// DataSet public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } /// /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) /// /// 数据库连接 /// 存储过程名 /// 存储过程参数 /// SqlCommand private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } /// /// 返回查询结果集 LWP 2012-10-10 /// /// Sql语句 /// 存储过程参数 /// 结果集 public static DataSet Query(string strSql, params SqlParameter[] commandParameters) { return ExecuteDataset(ConnectionStringLocalTransaction, CommandType.Text, strSql, commandParameters); } #region ExecuteDataset /// /// 返回查询结果集 /// /// Sql语句 /// public static DataSet ExecuteDataset(string cmdText) { return ExecuteDataset(ConnectionStringLocalTransaction, CommandType.Text, cmdText); } #endregion //------------------------------------------------------------------------------------------------------------------------------- /// /// 直接执行语句返回数据集 /// /// 数据库连接字符串 /// 查询语句 /// public static DataSet OpenSqlDataSet(string connectionstring, string sqltext) { SqlConnection Conn = new SqlConnection(connectionstring); // Conn.ConnectionTimeout=600; Conn.Open(); SqlDataAdapter MyAdapter = new SqlDataAdapter(sqltext, Conn); DataSet MyDataSet = new DataSet(); try { MyAdapter.SelectCommand.CommandTimeout = 6000; MyAdapter.Fill(MyDataSet); Conn.Close(); } catch { MyDataSet = null; Conn.Close(); } return MyDataSet; } /// /// 直接执行语句返回执行结果true/false /// /// 数据库连接字符串 /// 执行语句 /// public static bool ExecuteSqlCommand(string connectionstring, string sqltext) { bool bRtn; try { SqlConnection Conn = new SqlConnection(connectionstring); Conn.Open(); SqlTransaction myTrans = Conn.BeginTransaction(); SqlCommand MyCommand = new SqlCommand(sqltext, Conn, myTrans); MyCommand.CommandTimeout = 6000; try { MyCommand.ExecuteNonQuery(); myTrans.Commit(); Conn.Close(); bRtn = true; } catch { myTrans.Rollback(); bRtn = false; } } catch { bRtn = false; } return bRtn; } /// /// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事物处理 /// 使用参数数组提供参数 /// /// /// 使用示例: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个存在的 sql 事物处理 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 public static DataSet ExecuteQueryDataset(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { DataSet ds = null; SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { 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 ds; } // } }