using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Data.Common; using System.Collections.Generic; namespace MvcWeb.DAL { /// <summary> /// 数据访问基础类 /// </summary> public static class DbHelperSQL { private const string configName = "ApplicationServices"; private static string connectionString; public static string ConnectionString { get { return connectionString; } } static DbHelperSQL() { try { connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString; } catch (Exception ex) { throw new Exception(string.Format("读取连接字符串失败! ConnectionStrings:{0}; Error:{1}", configName, ex.Message)); } }
#region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行SQL语句,返回影响的记录数,设置超时时间 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="TimesOut">超时时间</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlByTime(string SQLString, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = TimesOut; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static int ExecuteSqlTran(List<String> SQLStringList) { DateTime now = DateTime.Now; try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return -1; } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string s in SQLStringList) { sb.Append(s); sb.Append(";"); } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行带一个参数的的SQL语句。 参数名 @content /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}, 参数:{2}", l, SQLString, content), "\\SqlLog"); } } } /// <summary> /// 向数据库里插入图像格式的字段 @fs /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { DateTime now = DateTime.Now; try { 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; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行带一个带参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static object ExecuteSqlGet(string SQLString, string content) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); 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) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, content), "\\SqlLog"); } } } public static object GetSingle(string SQLString, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = TimesOut; 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; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string strSQL) { DateTime now = DateTime.Now; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, strSQL), "\\SqlLog"); } } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } public static DataSet Query(string SQLString, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = TimesOut; command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static int ExecuteSqlTran(Dictionary<string, SqlParameter[]> SQLStringList) { DateTime now = DateTime.Now; try { int count = 0; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { //循环 foreach (string myDE in SQLStringList.Keys) { string cmdText = myDE; SqlParameter[] cmdParms = SQLStringList[cmdText]; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); count += val; cmd.Parameters.Clear(); } trans.Commit(); return count; } catch (Exception ex) { trans.Rollback(); throw ex; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (SQLStringList != null) { foreach (KeyValuePair<string, SqlParameter[]> kv in SQLStringList) { sb.AppendFormat("\n语句:{0}, 参数[", kv.Key); if (kv.Value != null) { foreach (SqlParameter sp in kv.Value) { sb.AppendFormat("{0},{1};", sp.ParameterName, sp.Value.ToStr()); } } } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, {1}", l, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataTable</returns> public static DataTable QueryTables(string SQLString, params SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } // finally // { // cmd.Dispose(); // connection.Close(); // } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } var saveP = l > 2000 ? "\\SqlLog_Over_2000" : (l > 200 ? "\\SqlLog_Over_200" : "\\SqlLog"); WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), saveP); } } } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 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 = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters) { DateTime now = DateTime.Now; try { 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); connection.Close(); return dataSet; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach (IDataParameter sp in parameters) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, storedProcName, sb.ToString()), "\\SqlLog"); } } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = TimesOut; sqlDA.Fill(dataSet); connection.Close(); return dataSet; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach (IDataParameter sp in parameters) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, storedProcName, sb.ToString()), "\\SqlLog"); } } } public static bool RunProcedureNoQuery(string storedProcName, IDataParameter[] parameters) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); int i = command.ExecuteNonQuery(); connection.Close(); if (i > 0) return true; return false; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach (IDataParameter sp in parameters) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, storedProcName, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 构建 SqlCommand 对象(用来返回一个结果集) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand</returns> 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; } /// <summary> /// 创建 SqlCommand 对象实例(用来返回一个值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand 对象实例</returns> private static SqlCommand BuildValueCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.VarChar, 8000, ParameterDirection.Output, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } #endregion #region 自定义方法 public static DataTable GetTable(string SQLString) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, null); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { //string Tb = GetTableName(SQLString); da.Fill(ds, "ds"); cmd.Parameters.Clear(); cmd.Dispose(); da.Dispose(); return ds.Tables[0]; } catch (SqlException ex) { throw new Exception(ex.Message); } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } #endregion #region 通用方法 public static SqlConnection GetCon() { return new SqlConnection(connectionString); } public static void CloseCon(SqlConnection con) { if(con.State != ConnectionState.Closed) { con.Close(); con.Dispose(); } } public static bool Exists(SqlConnection con, string SQLString) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, con, null, SQLString, null); DataSet ds = new DataSet(); try { object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return false; } return true; } catch (SqlException ex) { throw new Exception(ex.Message); } } #endregion #region 扩展方法 by guoqicai /// <summary> /// 执行存储过程 PRO_SYS_GETMAXNO 获取 编码最大值 暂时确实 SYS_MAX_NO 表 不用 /// </summary> /// <param name="TABLE_NAME"></param> /// <param name="OFFICE_CODE"></param> /// <returns></returns> public static string GET_MAXNO(string TABLE_NAME,string OFFICE_CODE) { List<System.Data.SqlClient.SqlParameter> list = new List<System.Data.SqlClient.SqlParameter>(); list.Add(new System.Data.SqlClient.SqlParameter("@TABLE_NAME", TABLE_NAME)); list.Add(new System.Data.SqlClient.SqlParameter("@COLUMN_NAME", "")); list.Add(new System.Data.SqlClient.SqlParameter("@OFFICE_CODE", OFFICE_CODE)); list.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", SqlDbType.VarChar, 50)); System.Data.SqlClient.SqlParameter[] sps = list.ToArray(); sps[sps.Length - 1].Direction = ParameterDirection.Output; DataSet ds = DbHelperSQL.RunProcedure("PRO_SYS_GETMAXNO", list.ToArray()); string no = sps[sps.Length - 1].Value.ToStr(); if (!string.IsNullOrEmpty(no)) return no; throw new Exception("从存储过程 PRO_SYS_GETMAXNO 获取编码失败!"); } #endregion } }
using System;using System.Collections;using System.Collections.Specialized;using System.Data;using System.Data.SqlClient;using System.Configuration;using System.Data.Common;using System.Collections.Generic;
namespace MvcWeb.DAL{ /// <summary> /// 数据访问基础类 /// </summary> public static class DbHelperSQL { private const string configName = "ApplicationServices"; //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. private static string connectionString;
public static string ConnectionString { get { return connectionString; } }
static DbHelperSQL() { try { connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString; } catch (Exception ex) { throw new Exception(string.Format("读取连接字符串失败! ConnectionStrings:{0}; Error:{1}", configName, ex.Message)); } }
#region 公用方法 /// <summary> /// 判断是否存在某表的某个字段 /// </summary> /// <param name="tableName">表名称</param> /// <param name="columnName">列名称</param> /// <returns>是否存在</returns> public static bool ColumnExists(string tableName, string columnName) { string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; object res = GetSingle(sql); if (res == null) { return false; } return Convert.ToInt32(res) > 0; } /// <summary> /// 表是否存在 /// </summary> /// <param name="TableName"></param> /// <returns></returns> public static bool TabExists(string TableName) { string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1"; //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')"; object obj = GetSingle(strsql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params SqlParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion
#region 执行简单SQL语句
/// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } }
/// <summary> /// 执行SQL语句,返回影响的记录数,设置超时时间 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="TimesOut">超时时间</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlByTime(string SQLString, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = TimesOut; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static int ExecuteSqlTran(List<String> SQLStringList) { DateTime now = DateTime.Now; try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return -1; } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string s in SQLStringList) { sb.Append(s); sb.Append(";"); } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行带一个参数的的SQL语句。 参数名 @content /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}, 参数:{2}", l, SQLString, content), "\\SqlLog"); } } }
/// <summary> /// 向数据库里插入图像格式的字段 @fs /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } }
/// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { DateTime now = DateTime.Now; try { 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; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行带一个带参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static object ExecuteSqlGet(string SQLString, string content) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); 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) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, content), "\\SqlLog"); } } } public static object GetSingle(string SQLString, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = TimesOut; 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; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string strSQL) { DateTime now = DateTime.Now; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, strSQL), "\\SqlLog"); } }
} /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } public static DataSet Query(string SQLString, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = TimesOut; command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } }
#endregion
#region 执行带参数的SQL语句
/// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } }
/// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static int ExecuteSqlTran(Dictionary<string, SqlParameter[]> SQLStringList) { DateTime now = DateTime.Now; try { int count = 0; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { //循环 foreach (string myDE in SQLStringList.Keys) { string cmdText = myDE; SqlParameter[] cmdParms = SQLStringList[cmdText]; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); count += val; cmd.Parameters.Clear(); } trans.Commit(); return count; } catch (Exception ex) { trans.Rollback(); throw ex; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (SQLStringList != null) { foreach (KeyValuePair<string, SqlParameter[]> kv in SQLStringList) { sb.AppendFormat("\n语句:{0}, 参数[", kv.Key); if (kv.Value != null) { foreach (SqlParameter sp in kv.Value) { sb.AppendFormat("{0},{1};", sp.ParameterName, sp.Value.ToStr()); } } } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, {1}", l, sb.ToString()), "\\SqlLog"); } } }
/// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataTable</returns> public static DataTable QueryTables(string SQLString, params SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } }
/// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), "\\SqlLog"); } } //finally //{ //cmd.Dispose(); //connection.Close(); //}
}
/// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, SqlParameter[] cmdParms) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (cmdParms != null) { foreach (SqlParameter sp in cmdParms) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } var saveP = l > 2000 ? "\\SqlLog_Over_2000" : (l > 200 ? "\\SqlLog_Over_200" : "\\SqlLog"); WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, SQLString, sb.ToString()), saveP); } } }
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 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 = CommandType.Text;//cmdType; if (cmdParms != null) {
foreach (SqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } }
#endregion
#region 存储过程操作
/// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters) { DateTime now = DateTime.Now; try { 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); connection.Close(); return dataSet; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach (IDataParameter sp in parameters) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, storedProcName, sb.ToString()), "\\SqlLog"); } } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, int TimesOut) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = TimesOut; sqlDA.Fill(dataSet); connection.Close(); return dataSet; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach (IDataParameter sp in parameters) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, storedProcName, sb.ToString()), "\\SqlLog"); } } } public static bool RunProcedureNoQuery(string storedProcName, IDataParameter[] parameters) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); int i = command.ExecuteNonQuery(); connection.Close(); if (i > 0) return true; return false; } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach (IDataParameter sp in parameters) { sb.AppendFormat("{0}:{1};", sp.ParameterName, sp.Value.ToString()); } } WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1},参数:{2}", l, storedProcName, sb.ToString()), "\\SqlLog"); } } } /// <summary> /// 构建 SqlCommand 对象(用来返回一个结果集) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand</returns> 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; } /// <summary> /// 创建 SqlCommand 对象实例(用来返回一个值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand 对象实例</returns> private static SqlCommand BuildValueCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.VarChar, 8000, ParameterDirection.Output, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } #endregion
#region 自定义方法 public static DataTable GetTable(string SQLString) { DateTime now = DateTime.Now; try { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, null); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { //string Tb = GetTableName(SQLString); da.Fill(ds, "ds"); cmd.Parameters.Clear(); cmd.Dispose(); da.Dispose(); return ds.Tables[0]; } catch (SqlException ex) { throw new Exception(ex.Message); } } } } finally { long l = (long)(DateTime.Now - now).TotalMilliseconds; if (l > 50) { WriteLogToFile.WriteLog(string.Format("语句执行时间:{0}ms, 语句:{1}", l, SQLString), "\\SqlLog"); } } } #endregion
#region 通用方法 public static SqlConnection GetCon() { return new SqlConnection(connectionString); } public static void CloseCon(SqlConnection con) { if(con.State != ConnectionState.Closed) { con.Close(); con.Dispose(); } } public static bool Exists(SqlConnection con, string SQLString) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, con, null, SQLString, null); DataSet ds = new DataSet(); try { object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return false; } return true; } catch (SqlException ex) { throw new Exception(ex.Message); } } #endregion
#region 扩展方法 by guoqicai
/// <summary> /// 执行存储过程 PRO_SYS_GETMAXNO 获取 编码最大值 暂时确实 SYS_MAX_NO 表 不用 /// </summary> /// <param name="TABLE_NAME"></param> /// <param name="OFFICE_CODE"></param> /// <returns></returns> public static string GET_MAXNO(string TABLE_NAME,string OFFICE_CODE) { List<System.Data.SqlClient.SqlParameter> list = new List<System.Data.SqlClient.SqlParameter>(); list.Add(new System.Data.SqlClient.SqlParameter("@TABLE_NAME", TABLE_NAME)); list.Add(new System.Data.SqlClient.SqlParameter("@COLUMN_NAME", "")); list.Add(new System.Data.SqlClient.SqlParameter("@OFFICE_CODE", OFFICE_CODE)); list.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", SqlDbType.VarChar, 50)); System.Data.SqlClient.SqlParameter[] sps = list.ToArray(); sps[sps.Length - 1].Direction = ParameterDirection.Output; DataSet ds = DbHelperSQL.RunProcedure("PRO_SYS_GETMAXNO", list.ToArray()); string no = sps[sps.Length - 1].Value.ToStr(); if (!string.IsNullOrEmpty(no)) return no; throw new Exception("从存储过程 PRO_SYS_GETMAXNO 获取编码失败!"); }
#endregion
}}