阿里云爆款
首页 » .NET » C#-继承IDbConnection连接不同数据库,通用的DbHelper(2)

C#-继承IDbConnection连接不同数据库,通用的DbHelper(2)

原文 http://blog.csdn.net/coolhe21cn/article/details/79052433

2018-01-14 02:00:15阅读(137)

阿里云爆款

在《C#-继承IDbConnection连接不同数据库,通用的DbHelper(1)》之后,感觉和原来的DbHelper使用方法不同,为了采用统一的parameter方法,进行了以下修改。

增加以下类
1. Parameters.cs  # 带参数的parameter
2. PubConstant.cs  # 数据库常量
3. DESEncrypt.cs  # 加密类
1. Parameters.cs # 带参数的parameter
 public struct Parameters
    {
        public string ParamName;
        public object ParamValue;
        public ParameterDirection ParamDirection;
        public Parameters(string Name, object Value, ParameterDirection Direction)
        {
            ParamName = Name;
            ParamValue = Value;
            ParamDirection = Direction;
        }
        public Parameters(string Name, object Value)
        {
            ParamName = Name;
            ParamValue = Value;
            ParamDirection = ParameterDirection.Input;
        }
    }      
2. PubConstant.cs # 数据库常量
/// <summary>
    /// 公共常量
    /// </summary>
    public class PubConstant
    {
        /// <summary>
        /// 获取数据库类型
        /// </summary>
        public static string DbProvider
        {
            get { return ConfigurationManager.AppSettings["DbProvider"]; }
        }
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                string _connectionString = ConfigurationManager.AppSettings["ConnectionString"];
                string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
                if (ConStringEncrypt == "true")
                {
                    //_connectionString = DESEncrypt.Decrypt(_connectionString);
                    _connectionString = DESEncrypt.Encrypt(_connectionString);
                }
                return _connectionString;
            }
        }
        /// <summary>
        /// 得到web.config里配置项的数据库连接字符串。
        /// </summary>
        /// <param name="configName"></param>
        /// <returns></returns>
        public static string GetConnectionString(string configName)
        {
            string connectionString = ConfigurationManager.AppSettings[configName];
            string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
            if (ConStringEncrypt == "true")
            {
                connectionString = DESEncrypt.Decrypt(connectionString);
            }
            return connectionString;
        }
    }
3. DESEncrypt.cs # 加密类
/// <summary>
    /// DES加密/解密类。
    /// </summary>
    public class DESEncrypt
    {
        //private static string encryptKey = "litianping";
        private static string encryptKey = "youersi5971";
        public DESEncrypt() { }
        #region ========加密========
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, encryptKey);
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }
        #endregion
        #region ========解密========
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, encryptKey);
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
        #endregion
        #region ========MD5 32 位 ========
        /// <summary>
        /// MD5 32 位 
        /// </summary>
        /// <param name="convertString"></param>
        /// <returns></returns>
        public static String Encrypt32(String convertString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(convertString);
            bytes = md5.ComputeHash(bytes);
            md5.Clear();
            string ret = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
            }
            return ret.PadLeft(32, '0').ToLower();
        }
        #endregion
        #region ========MD5 16 位  ========
        /// <summary>
        /// MD5 16 位  
        /// </summary>
        /// <param name="convertString"></param>
        /// <returns></returns>
        public static string Encrypt16(string convertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(convertString)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2.ToLower();
        }
        #endregion
    }
app.config
<?xml version="1.0"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <appSettings>
    <add key="ConStringEncrypt" value="false"/>
    <add key="DbProvider" value="SqlServer"/>
    <!-- 通过改变value值来更换数据库  
    <add key="DataProvider" value="Oracle"/>  
    <add key="DataProvider" value="SqlServer"/>  
    <add key="DataProvider" value="OleDb"/>  
    <add key="DataProvider" value="Odbc"/>   
    <add key="DataProvider" value="MySql"/>  
    <add key="DataProvider" value="SQLite"/> 
    -->    
  </appSettings>
  <connectionStrings>        
    <add name="ConnString" connectionString="server=.;database=BookManage;Persist Security Info=False;uid=sa;pwd=sa123"/>
    <!-- 通过改变ConnectionString的值来更换数据库连接字符串  
    <add name ="ConnString" connectionString="Data Source=.\data\BookManageDB.db"/>
    <add name="ConnString" connectionString="server=.;database=CourseManageDB;Persist Security Info=False;uid=sa;pwd=sa123"/>
    <add name ="ConnString" connectionString="Server=.;Database=CourseManageDB;Uid=sa;Pwd=sa123"/>
    <add name ="ConnectionStringMssql" connectionString="Server=.;Database=BookManage;Uid=sa;Pwd=sa123"/>
    <add name="ConnString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DBDemo.mdb;Jet OLEDB:Database Password=1234"/>  
    <add name="ConnString" connectionString="server=localhost;database=yourDbName;Persist Security Info=False;Integrated Security=SSPI"/>  
    <add name="ConnString" connectionString="server=localhost;database=yourDbName;Persist Security Info=False;uid=sa;pwd=1234"/>  
    <add name="ConnString" connectionString="server=localhost;database=yourDbName;Persist Security Info=False;uid=root;pwd=mysqladmin"/>  
    <add name ="connString" connectionString="Data Source=.\data\BookManageDB.db"/>
    -->
   </connectionStrings>
</configuration>
修改 IDbManager.cs
void AddParameters(params Parameters[] cmdParms);
修改 DbManager.cs
public void AddParameters(params Parameters[] cmdParms)
        {
            // 根据数组创建paramter对象列表
            this.CreateParameters(cmdParms.Length);
            for (int index = 0; index < cmdParms.Length; index++)
            {                 
                Parameters[index].ParameterName = cmdParms[index].ParamName;
                Parameters[index].Value = cmdParms[index].ParamValue;
            }
        }
测试
private static void SelectWithParams2(int CourseId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from course");
            strSql.Append(" where ");
            strSql.Append(" CourseId < @CourseId  ");
            //先创建参数,然后才能添加参数   
            //DbHelper.CreateParameters(1);  //参数个数,1个  
            //DbHelper.AddParameters(0, "@CourseId", CourseId);
            Parameters[] parameters = {
                        new Parameters("@CourseId", CourseId)
            };  // 增加带参数的sql对应字段
            DbHelper.AddParameters(parameters);  // 注意增加带参数的sql对应字段
            Console.WriteLine(strSql.ToString());
            int num = Convert.ToInt32(DbHelper.ExecuteScalar(strSql.ToString()));  
            Console.WriteLine("num:" + num.ToString());
            //IDataReader reader = DbHelper.ExecuteReader(strSql.ToString());
            //while (reader.Read())
            //{
            //    Console.WriteLine(reader["CourseId"].ToString());
            //}
            DbHelper.Close();
        }  

下面还希望能做成如下写法:
public static int ExecuteSql(string SQLString, params Parameters[] cmdParms)

DbHelper.ExecuteSql(strSql.ToString(), parameters )
待续…

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹