using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Configuration; namespace DSWeb.DataAccess { /// /// 数据库的通用访问代码 /// 此类为抽象类,不允许实例化,在应用时直接调用即可 /// public abstract class SqlHelper { //获取数据库连接字符串,其属于静态变量且只读,项目中所有文档可以直接使用,但不能修改 public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["DongShengDB"].ConnectionString; //public static readonly string CSLTDSDB = ConfigurationManager.ConnectionStrings["dscustserviceDB"].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; // 哈希表用来存储缓存的参数信息,哈希表可以存储任意类型的参数。 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, 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 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; } /// /// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事物处理 /// 使用参数数组提供参数 /// /// /// 使用示例: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// /// 一个存在的 sql 事物处理 /// SqlCommand命令类型 (存储过程, T-SQL语句, 等等。) /// 存储过程的名字或者 T-SQL 语句 /// 以数组形式提供SqlCommand命令中用到的参数列表 /// 返回一个数值表示此SqlCommand命令执行后影响的行数 public static SqlDataReader ExecuteQueryReader(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); SqlDataReader val = cmd.ExecuteReader(); 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; } /// /// 执行一条返回结果集的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(); conn.Dispose(); 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; } /// /// 执行 SQL 语句 /// /// SQL 语句 /// 参数集 /// public static DataTable ExecuteSql(string sql) { //创建命令 SqlCommand comm = new SqlCommand() { CommandText = sql//SQL语句 }; return ExecuteSearch(comm, null); } /// /// 执行 SQL 语句 /// /// 执行的命令 /// 参数集 /// 查询的结果集 private static DataTable ExecuteSearch(SqlCommand comm, params SqlParameter[] p) { //获得返回集实例 //_result = Utility.Result.GetInstance(); DataTable dt = new DataTable(); //创建连接 using (SqlConnection conn = new SqlConnection(ConnectionStringLocalTransaction)) { //设置参数 if (p != null && p.Length > 0) { foreach (SqlParameter item in p) { comm.Parameters.Add(item); } } comm.Connection = conn; SqlDataAdapter da = new SqlDataAdapter(comm); //填充数据 da.Fill(dt); conn.Close(); conn.Dispose(); } return dt; } /// /// 执行一条计算查询结果语句,返回查询结果(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; } } } } /// /// 缓存参数数组 /// /// 参数缓存的键值 /// 被缓存的参数列表 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, 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(); connection.Dispose(); } } } return ds; } #endregion #region 直接执行语句返回数据集或执行结果true/false /// /// 直接执行语句返回数据集 /// /// 数据库连接字符串 /// 查询语句 /// public static DataSet OpenSqlDataSet(string connectionstring, string sqltext) { SqlConnection Conn = new SqlConnection(connectionstring); // Conn.ConnectionTimeout=600; Conn.Open(); DataSet MyDataSet = new DataSet(); try { SqlDataAdapter MyAdapter = new SqlDataAdapter(sqltext, Conn); MyAdapter.SelectCommand.CommandTimeout = 600000; MyAdapter.Fill(MyDataSet); } catch(Exception e) { MyDataSet = null; throw e; } finally { Conn.Close(); Conn.Dispose(); } return MyDataSet; } /// /// 直接执行语句返回数据集 /// /// 数据库连接字符串 /// 存储过程名 /// 查询语句或参数集 /// public static DataSet RunProcedure(string connectionstring, string StoredProcedureName, SqlParameter[] myParamArray) { SqlConnection Conn = new SqlConnection(connectionstring); Conn.Open(); SqlCommand MyCommand = new SqlCommand(StoredProcedureName, Conn); MyCommand.CommandTimeout = 6000; MyCommand.CommandType = CommandType.StoredProcedure; MyCommand.CommandText = StoredProcedureName; MyCommand.Parameters.Clear(); for (int j = 0; j < myParamArray.Length; j++) { MyCommand.Parameters.Add(myParamArray[j]); } SqlDataAdapter MyAdapter = new SqlDataAdapter(); MyAdapter.SelectCommand = MyCommand; DataSet MyDataSet = new DataSet(); MyAdapter.Fill(MyDataSet); Conn.Close(); Conn.Dispose(); 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 = 600000; try { MyCommand.ExecuteNonQuery(); myTrans.Commit(); bRtn = true; } catch { myTrans.Rollback(); bRtn = false; } finally { Conn.Close(); Conn.Dispose(); } } catch { bRtn = false; } return bRtn; } /// /// 直接执行语句返回执行结果true/false,无事务 /// /// 数据库连接字符串 /// 执行语句 /// public static bool ExecuteSql(string connectionstring, string sqltext) { bool bRtn; try { SqlConnection Conn = new SqlConnection(connectionstring); Conn.Open(); SqlCommand MyCommand = new SqlCommand(sqltext, Conn); MyCommand.CommandTimeout = 6000; try { MyCommand.ExecuteNonQuery(); bRtn = true; } catch (Exception execError) { bRtn = false; throw execError; } finally { Conn.Close(); Conn.Dispose(); } } catch (Exception execError2) { bRtn = false; throw execError2; } return bRtn; } /// /// 直接执行语句返回执行结果true/false /// /// 数据库连接字符串 /// 存储过程名 /// 执行语句或参数集 /// public static bool ExecuteSqlStoredProcedure(string connectionstring, string StoredProcedureName, SqlParameter[] myParamArray) { bool bRtn; try { SqlConnection Conn = new SqlConnection(connectionstring); Conn.Open(); SqlTransaction myTrans = Conn.BeginTransaction(); SqlCommand MyCommand = new SqlCommand(); MyCommand.Connection = Conn; MyCommand.Transaction = myTrans; MyCommand.CommandTimeout = 6000; MyCommand.CommandType = CommandType.StoredProcedure; MyCommand.CommandText = StoredProcedureName; MyCommand.Parameters.Clear(); for (int j = 0; j < myParamArray.Length; j++) { MyCommand.Parameters.Add(myParamArray[j]); } try { MyCommand.ExecuteNonQuery(); myTrans.Commit(); bRtn = true; } catch { myTrans.Rollback(); bRtn = false; } finally { Conn.Close(); Conn.Dispose(); } } catch { bRtn = false; } return bRtn; } /// /// 直接执行语句返回执行结果true/false /// /// 数据库连接字符串 /// 存储过程名 /// 执行语句或参数集 /// public static int ExecuteSqlStoredProcedureReturn(SqlConnection Conn, string StoredProcedureName, SqlParameter[] myParamArray) { int iResult = 0; try { //SqlConnection Conn = new SqlConnection(connectionstring); Conn.Open(); SqlTransaction myTrans = Conn.BeginTransaction(); SqlCommand MyCommand = new SqlCommand(); MyCommand.Connection = Conn; MyCommand.Transaction = myTrans; MyCommand.CommandTimeout = 6000; MyCommand.CommandType = CommandType.StoredProcedure; MyCommand.CommandText = StoredProcedureName; MyCommand.Parameters.Clear(); for (int j = 0; j < myParamArray.Length; j++) { MyCommand.Parameters.Add(myParamArray[j]); } MyCommand.Parameters.Add("@RETURN_VALUE", "").Direction = ParameterDirection.ReturnValue; try { MyCommand.ExecuteNonQuery(); iResult = int.Parse(MyCommand.Parameters["@RETURN_VALUE"].Value.ToString().Trim()); myTrans.Commit(); //iResult = 1; } catch(Exception ee) { myTrans.Rollback(); iResult = -1; throw ee; } finally { Conn.Close(); Conn.Dispose(); } } catch(Exception eee) { iResult = -1; throw eee; } return iResult; } /// /// 直接执行语句返回执行结果true/false /// /// 数据库连接字符串 /// 存储过程名 /// 执行语句或参数集 /// public static string ExecuteSqlStoredProcedureReturnString(SqlConnection Conn, string StoredProcedureName, SqlParameter[] myParamArray) { string sResult = ""; try { //SqlConnection Conn = new SqlConnection(connectionstring); Conn.Open(); SqlTransaction myTrans = Conn.BeginTransaction(); SqlCommand MyCommand = new SqlCommand(); MyCommand.Connection = Conn; MyCommand.Transaction = myTrans; MyCommand.CommandTimeout = 6000; MyCommand.CommandType = CommandType.StoredProcedure; MyCommand.CommandText = StoredProcedureName; MyCommand.Parameters.Clear(); for (int j = 0; j < myParamArray.Length; j++) { MyCommand.Parameters.Add(myParamArray[j]); } MyCommand.Parameters.Add("@RETURN_VALUE", SqlDbType.VarChar,100).Direction = ParameterDirection.Output; try { MyCommand.ExecuteNonQuery(); sResult = MyCommand.Parameters["@RETURN_VALUE"].Value.ToString().Trim(); myTrans.Commit(); //iResult = 1; } catch(Exception ee) { myTrans.Rollback(); sResult = "error"; throw ee; } finally { Conn.Close(); Conn.Dispose(); } } catch(Exception eee) { sResult = "error"; throw eee; } return sResult; } #endregion public static void CloseConnection() { if (_sqlConnection != null) { if (_sqlConnection.State == ConnectionState.Open) { _sqlConnection.Close(); _sqlConnection.Dispose(); } } } /// /// 执行一条返回第一条记录第一列的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; } // } }