using NFine.Code; using System; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.IO; using System.Security.Cryptography; using System.Text; namespace NFine.Data.Extensions { public class DbHelper { /// /// 调试日志 /// //public static LogHelper log = LogFactory.GetLogger(typeof(DbHelper)); /// /// 连接字符串 /// public static string ConnectionString { get; set; } /// /// 数据库类型 /// public static DatabaseType DbType { get; set; } /// /// 数据库命名参数符号 /// public static string DbParmChar { get; set; } public DbHelper(string connstring) { string ConStringDESEncrypt = FromMd5(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString); ConnectionString = FromMd5(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString); if (ConStringDESEncrypt == "true") { ConnectionString = DESEncrypt.Decrypt(ConnectionString); } this.DatabaseTypeEnumParse(ConfigurationManager.ConnectionStrings["connstr"].ProviderName); DbParmChar = DbFactory.CreateDbParmCharacter(); } #region 字符串加解密 /// /// MD5加密 /// /// /// public static string ToMd5(string str) { return Encrypt(str, "&%#@?,:*_"); } /// /// MD5解密 /// /// /// public static string FromMd5(string str) { //return str; return Decrypt(str, "&%#@?,:*_"); } /// /// 加密 /// /// /// /// private static String Encrypt(String strText, String strEncrKey) { Byte[] byKey = { }; Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; try { byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { return ex.Message; } } /// /// 解密 /// /// /// /// private static String Decrypt(String strText, String sDecrKey) { Byte[] byKey = { }; Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; Byte[] inputByteArray = new byte[strText.Length]; try { byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception ex) { return ex.Message; } } #endregion /// /// 执行 SQL 语句,并返回受影响的行数。 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] parameters) { int num = 0; try { DbCommand cmd = DbFactory.CreateDbCommand(); using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, parameters); num = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } catch (Exception ex) { num = -1; //log.Error(ex.Message); } return num; } /// /// 执行 SQL 语句,并返回受影响的行数。 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// public static int ExecuteNonQuery(CommandType cmdType, string cmdText) { int num = 0; try { DbCommand cmd = DbFactory.CreateDbCommand(); using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, null); num = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } catch (Exception ex) { num = -1; //log.Error(ex.Message); } return num; } /// /// 执行 SQL 语句,并返回受影响的行数。 /// /// 数据库连接对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// public static int ExecuteNonQuery(DbConnection connection, CommandType cmdType, string cmdText, params DbParameter[] parameters) { int num = 0; try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, parameters); num = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } catch (Exception ex) { num = -1; //log.Error(ex.Message); } return num; } /// /// 执行 SQL 语句,并返回受影响的行数。 /// /// 数据库连接对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// public static int ExecuteNonQuery(DbConnection connection, CommandType cmdType, string cmdText) { int num = 0; try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, null); num = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } catch (Exception ex) { num = -1; //log.Error(ex.Message); } return num; } /// /// 执行 SQL 语句,并返回受影响的行数。 /// /// 事务对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// public static int ExecuteNonQuery(DbTransaction isOpenTrans, CommandType cmdType, string cmdText, params DbParameter[] parameters) { int num = 0; try { DbCommand cmd = DbFactory.CreateDbCommand(); if (isOpenTrans == null || isOpenTrans.Connection == null) { using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString)) { PrepareCommand(cmd, conn, isOpenTrans, cmdType, cmdText, parameters); num = cmd.ExecuteNonQuery(); } } else { PrepareCommand(cmd, isOpenTrans.Connection, isOpenTrans, cmdType, cmdText, parameters); num = cmd.ExecuteNonQuery(); } cmd.Parameters.Clear(); } catch (Exception ex) { num = -1; //log.Error(ex.Message); } return num; } /// /// 执行 SQL 语句,并返回受影响的行数。 /// /// 事务对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// public static int ExecuteNonQuery(DbTransaction isOpenTrans, CommandType cmdType, string cmdText) { int num = 0; try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, isOpenTrans.Connection, isOpenTrans, cmdType, cmdText, null); num = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } catch (Exception ex) { num = -1; //log.Error(ex.Message); } return num; } /// /// 使用提供的参数,执行有结果集返回的数据库操作命令、并返回SqlDataReader对象 /// /// 事务对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行< /// 执行命令所需的sql语句对应参数 /// 返回SqlDataReader对象 public static IDataReader ExecuteReader(DbTransaction isOpenTrans, CommandType cmdType, string cmdText, params DbParameter[] parameters) { DbCommand cmd = DbFactory.CreateDbCommand(); DbConnection conn = DbFactory.CreateDbConnection(ConnectionString); try { PrepareCommand(cmd, conn, isOpenTrans, cmdType, cmdText, parameters); IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch (Exception ex) { conn.Close(); cmd.Dispose(); //log.Error(ex.Message); throw; } } 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; } } /// /// 返回一个数据表 /// /// 数据库连接字符串 /// 命令类型 /// SQL语句 /// 参数 /// 数据表名 /// 是否加载数据表结构 /// public static DataTable ExecuteTable(string connectionString, CommandType cmdType, string cmdText, bool bIsLoadStru, params SqlParameter[] commandParameters) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataTable dt = ExecuteTable(connection, cmdType, cmdText, bIsLoadStru, commandParameters); connection.Close(); return dt; } } /// /// 返回一个数据表 /// /// 数据库连接 /// 命令类型 /// SQL语句 /// 参数 /// 数据表名 /// 是否加载数据表结构 /// public static DataTable ExecuteTable(SqlConnection connection, CommandType cmdType, string cmdText, bool bIsLoadStru, params SqlParameter[] commandParameters) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); SqlDataAdapter da = new SqlDataAdapter(cmd); if (bIsLoadStru) { da.FillSchema(ds, SchemaType.Source); } da.Fill(ds); cmd.Parameters.Clear(); return ds.Tables[0]; } public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /// /// 使用提供的参数,执行有结果集返回的数据库操作命令、并返回SqlDataReader对象 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行< /// 执行命令所需的sql语句对应参数 /// 返回SqlDataReader对象 public static IDataReader ExecuteReader(CommandType cmdType, string cmdText, params DbParameter[] parameters) { DbCommand cmd = DbFactory.CreateDbCommand(); DbConnection conn = DbFactory.CreateDbConnection(ConnectionString); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, parameters); IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch (Exception ex) { conn.Close(); cmd.Dispose(); //log.Error(ex.Message); throw; } } /// ///使用提供的参数,执行有结果集返回的数据库操作命令、并返回SqlDataReader对象 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行< /// 返回SqlDataReader对象 public static IDataReader ExecuteReader(CommandType cmdType, string cmdText) { DbCommand cmd = DbFactory.CreateDbCommand(); DbConnection conn = DbFactory.CreateDbConnection(ConnectionString); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, null); IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch (Exception ex) { conn.Close(); cmd.Dispose(); //log.Error(ex.Message); throw; } } /// /// 查询数据填充到数据集DataSet中 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 命令文本 /// sql语句对应参数 /// 数据集DataSet对象 public static DataSet GetDataSet(CommandType cmdType, string cmdText, params DbParameter[] parameters) { DataSet ds = new DataSet(); DbCommand cmd = DbFactory.CreateDbCommand(); DbConnection conn = DbFactory.CreateDbConnection(ConnectionString); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, parameters); IDbDataAdapter sda = DbFactory.CreateDataAdapter(cmd); sda.Fill(ds); return ds; } catch (Exception ex) { conn.Close(); cmd.Dispose(); //log.Error(ex.Message); throw; } } /// /// 查询数据填充到数据集DataSet中 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 命令文本 /// 数据集DataSet对象 public static DataSet GetDataSet(CommandType cmdType, string cmdText) { DataSet ds = new DataSet(); DbCommand cmd = DbFactory.CreateDbCommand(); DbConnection conn = DbFactory.CreateDbConnection(ConnectionString); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, null); IDbDataAdapter sda = DbFactory.CreateDataAdapter(cmd); sda.Fill(ds); return ds; } catch (Exception ex) { conn.Close(); cmd.Dispose(); //log.Error(ex.Message); throw; } } /// /// 依靠数据库连接字符串connectionString, /// 使用所提供参数,执行返回首行首列命令 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// 返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。 public static object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] parameters) { try { DbCommand cmd = DbFactory.CreateDbCommand(); using (DbConnection connection = DbFactory.CreateDbConnection(ConnectionString)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, parameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } catch (Exception ex) { //log.Error(ex.Message); throw; } } /// /// 依靠数据库连接字符串connectionString, /// 使用所提供参数,执行返回首行首列命令 /// /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。 public static object ExecuteScalar(CommandType cmdType, string cmdText) { try { DbCommand cmd = DbFactory.CreateDbCommand(); using (DbConnection connection = DbFactory.CreateDbConnection(ConnectionString)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, null); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } catch (Exception ex) { //log.Error(ex.Message); throw; } } /// ///依靠数据库连接字符串connectionString, /// 使用所提供参数,执行返回首行首列命令 /// /// 数据库连接对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// 返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。 public static object ExecuteScalar(DbConnection connection, CommandType cmdType, string cmdText, params DbParameter[] parameters) { try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, parameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } catch (Exception ex) { //log.Error(ex.Message); throw; } } /// ///依靠数据库连接字符串connectionString, /// 使用所提供参数,执行返回首行首列命令 /// /// 数据库连接对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// 返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。 public static object ExecuteScalar(DbConnection connection, CommandType cmdType, string cmdText) { try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, null); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } catch (Exception ex) { //log.Error(ex.Message); throw; } } /// ///依靠数据库连接字符串connectionString, /// 使用所提供参数,执行返回首行首列命令 /// /// 数据库连接对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// 返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。 public static object ExecuteScalar(DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText) { try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, conn, isOpenTrans, cmdType, cmdText, null); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } catch (Exception ex) { //log.Error(ex.Message); throw; } } /// ///依靠数据库连接字符串connectionString, /// 使用所提供参数,执行返回首行首列命令 /// /// 事务 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行 /// 执行命令所需的sql语句对应参数 /// 返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。 public static object ExecuteScalar(DbTransaction isOpenTrans, CommandType cmdType, string cmdText, params DbParameter[] parameters) { try { DbCommand cmd = DbFactory.CreateDbCommand(); PrepareCommand(cmd, isOpenTrans.Connection, isOpenTrans, cmdType, cmdText, parameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } catch (Exception ex) { //log.Error(ex.Message); throw; } } /// /// 为即将执行准备一个命令 /// /// SqlCommand对象 /// SqlConnection对象 /// DbTransaction对象 /// 执行命令的类型(存储过程或T-SQL,等等) /// 存储过程名称或者T-SQL命令行, e.g. Select * from Products /// SqlParameters to use in the command private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText, DbParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (isOpenTrans != null) cmd.Transaction = isOpenTrans; cmd.CommandType = cmdType; if (cmdParms != null) { cmd.Parameters.AddRange(cmdParms); } } /// /// 用于数据库类型的字符串枚举转换 /// /// /// /// public void DatabaseTypeEnumParse(string value) { try { switch (value) { case "System.Data.SqlClient": DbType = DatabaseType.SqlServer; break; case "System.Data.OracleClient": DbType = DatabaseType.Oracle; break; case "MySql.Data.MySqlClient": DbType = DatabaseType.MySql; break; case "System.Data.OleDb": DbType = DatabaseType.Access; break; case "System.Data.SQLite": DbType = DatabaseType.SQLite; break; default: break; } } catch { throw new Exception("数据库类型\"" + value + "\"错误,请检查!"); } } public static string GetErpIp() { string sql = "SELECT DBIpAddress,DBName FROM dbo.Sys_DataBase WHERE DBSourceName='SYS'"; DataTable dt = SqlHelper.GetDataTableBySql(sql); string ipSyy = dt.Rows[0]["DBIpAddress"].ToString(); string sql2 = "SELECT DBIpAddress,DBName FROM dbo.Sys_DataBase WHERE DBSourceName='ERP'"; DataTable dt2 = SqlHelper.GetDataTableBySql(sql2); string ipERP = dt2.Rows[0]["DBIpAddress"].ToString(); if (ipSyy == ipERP) return ""; else return "[" + dt2.Rows[0]["DBIpAddress"].ToString() + "]."; } public static string GetErpName() { string sql = "SELECT DBIpAddress,DBName FROM dbo.Sys_DataBase WHERE DBSourceName='ERP'"; DataTable dt = SqlHelper.GetDataTableBySql(sql); return dt.Rows[0]["DBName"].ToString(); } } }