C#-繼承IDbConnection連線不同資料庫,通用的DbHelper(2)
阿新 • • 發佈:2019-01-03
在《C#-繼承IDbConnection連線不同資料庫,通用的DbHelper(1)》之後,感覺和原來的DbHelper使用方法不同,為了採用統一的parameter方法,進行了以下修改。
增加以下類
1. Parameters.cs # 帶引數的parameter
2. PubConstant.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";
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 )
待續…