public DbConnection conn;//抽象類型
private DbCommand cmd;//抽象類型
private DbProviderFactory provider;
private DbParameter Para;//不同數(shù)據(jù)庫參數(shù)類型的抽象類型
private DbDataAdapter Adapter;//對應不同數(shù)據(jù)庫的數(shù)據(jù)適配器
Dictionary<Type, String> ParametersFormat;//不同數(shù)據(jù)庫參數(shù)格式化類型
public string retParaformat = string.Empty;//最終返回的格式化標志,如@{0},:{0}
public DataProviderFactory()
{
//從配置文件中取出標示數(shù)據(jù)庫類型的字符串并通過ProviderName的不同支持不同類型的數(shù)據(jù)庫
string providerName = ConfigurationManager.ConnectionStrings["ConnStr"].ProviderName;//也可以用索引,從1開始
//創(chuàng)建一個數(shù)據(jù)庫對應的實例,使用該實例就可以創(chuàng)建對應的connection,command 和adapater等等對象
provider = DbProviderFactories.GetFactory(providerName);
//創(chuàng)建具體的數(shù)據(jù)庫連接類型和命令執(zhí)行類型
conn = provider.CreateConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
cmd = provider.CreateCommand();
cmd.Connection = conn;
//創(chuàng)建具體的參數(shù)類型
Para = provider.CreateParameter();
//創(chuàng)建具體的適配器類型
Adapter = provider.CreateDataAdapter();
//不同數(shù)據(jù)庫參數(shù)前綴格式化
ParametersFormat = new Dictionary<Type, String>();
ParametersFormat.Add(typeof(System.Data.SqlClient.SqlCommand), "@{0}");//因SQL SERVER只返回{0}沒有@前綴,在此初始化處理
//返回格式化標志
retParaformat = GetParameterFormat(cmd);
}
上面那段代碼中,可以看到我定義了兩個公共變量,其中conn在外部只會有一個地方調(diào)用它,那就就是執(zhí)行DataReader方法的時候了,因為大家都知道dr在離開方法體時,連接是不能關閉的,
所以只能在外部調(diào)用處顯示關閉連接對象 ,必須定義為公共類型了,還有一個公共參數(shù)變量是格式化字符串的字符型。前面說到Oracle參數(shù)前綴是冒號:,其它幾個數(shù)據(jù)庫前綴是@符號,怎么樣在切換數(shù)據(jù)庫以后程序能動態(tài)識別參數(shù)前綴并組合相應的參數(shù)變量呢?如果手動寫代碼用數(shù)據(jù)庫對象類型枚舉去一個個判斷,那這數(shù)據(jù)庫工廠也沒什么意義了,最終找到了一個相當完美的解決方式(微軟就是微軟,都能替你想到,別人想不強大都難啦,呵呵),其實在做測試的時侯到各不同數(shù)據(jù)庫的參數(shù)前綴這就有點犯難了,手寫代碼一個個處理吧,沒問題,覺得應該有簡單的方法吧,MS從來就不是傻瓜呀,正好前兩天在園子首頁就有篇提到這個問題,而且給出相關提示,根據(jù)給的提示再gg了一把,終于找到了一個便捷的辦法。還是貼方法代碼好了,如下:
代碼如下:
/// <summary>
/// 根據(jù)不同的數(shù)據(jù)庫命令對象返回該類型數(shù)據(jù)庫參數(shù)的前綴格式化字符串
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
private string GetParameterFormat(DbCommand command)
{
if (!ParametersFormat.ContainsKey(command.GetType()))
{
this.Open();//讀取參數(shù)前綴時需打開數(shù)據(jù)庫連接
ParametersFormat.Add(
command.GetType(),
command.Connection.GetSchema("DataSourceInformation")
.Rows[0]["ParameterMarkerFormat"].ToString());
//conn.Close();在真正執(zhí)行語句的時候去關閉,避免重復打開
}
return ParametersFormat[command.GetType()];
}
就是這個了 ParameterMarkerFormat,即參數(shù)標志符格式化,如連接oracle數(shù)據(jù)庫則返回:{0},其它幾個數(shù)據(jù)庫返回@{0},惟獨SQL SERVER數(shù)據(jù)庫返回{0},到底是MS自己的東西,就是要返回跟別人不一樣的東西,也就因為這個,這個類庫里很遺憾不得不出現(xiàn)一個SqlCommand,就是上面貼出的構造函數(shù)里的初始化那ParametersFormat.Add(typeof(System.Data.SqlClient.SqlCommand), "@{0}");必須這樣做下處理,另外包括GetParameterFormat方法里的判斷,即不是SQL SERVER數(shù)據(jù)庫時才去讀參數(shù)前綴,如果是就直接返回@{0},有了這個格式化的前綴字符串,就好辦了.那參數(shù)名稱的賦值就可以類似這樣了string.Format("@{0}", ParaName);
下面說說各通用的方法和調(diào)用,之前的sqlhelper.cs,oraclehelper.cs,xxhelper.cs中的執(zhí)行方法大多都很多,有帶參數(shù)執(zhí)行的語句的方法,不帶參數(shù)執(zhí)行的語句的方法,帶參數(shù)執(zhí)行的方法體里面還要循環(huán)參數(shù),這些都我都精簡掉了,最終演變成了peacehelper.cs(開個玩笑).帶參執(zhí)行和不帶參執(zhí)行DML語句,其實是可以合并成一個方法,各個參數(shù)都是保存在數(shù)據(jù)庫命令對象的參數(shù)集合中的,我們可以把創(chuàng)建好的命令對象返回給外部程序調(diào)用處,調(diào)用的地方要帶參執(zhí)行語句的話,就定義參數(shù)并賦值就行了,不帶參執(zhí)行的話就不用定義參數(shù)了,這么以來就只需要寫一個方法就行了,而且執(zhí)行帶摻的語句時不用再循環(huán)參數(shù)集合了,因為在調(diào)用處定義參數(shù)時,該參數(shù)已經(jīng)綁定都了DbCommand對象了.寫一個返回給外部調(diào)用的數(shù)據(jù)庫命令對象的方法,如下:
代碼如下:
/// <summary>
/// 抽象參數(shù)集合類型
/// </summary>
/// <returns></returns>
public DbParameterCollection GetParmCollection()
{
return cmd.Parameters;
}
添加參數(shù)的方法如下:
代碼如下:
/// <summary>
/// 添加參數(shù)
/// </summary>
/// <param name="ParaName">參數(shù)名稱</param>
/// <param name="SqlType">參數(shù)數(shù)據(jù)類型</param>
/// <param name="ParaValue">參數(shù)值</param>
/// <param name="ParaCollect">參數(shù)對象的集合</param>
public void AddParam(string ParaName, DbType SqlType, object ParaValue, DbParameterCollection ParaCollect)
{
//不允許將一個DbCommand對象的Parameters插入到另外一個DbCommand對象,那么多個參數(shù)的話可以加上下面一句判斷
//如果已經(jīng)存在至少一個對象時,再深層拷貝一個
if (ParaCollect.Count >= 1)
{
Para = (DbParameter)((ICloneable)ParaCollect[0]).Clone();
}
Para.ParameterName = string.Format(retParaformat, ParaName);
Para.DbType = SqlType;
if (ParaValue == null)
{
Para.Value = string.Empty;//DBNull.Value;
}
else
{
Para.Value = ParaValue;
}
ParaCollect.Add(Para);
}
上面有句判斷,如果有多個參數(shù)會出異常,網(wǎng)上搜了下,注釋就是網(wǎng)上的解釋,不多說了,意思很清楚。這個方法里還有一點,如果DbType參數(shù)不要的話測試也是可以通過的,猜想如果不顯示指定參數(shù)數(shù)據(jù)類型的話,是不是都默認為object類型?這樣的話會不會涉及一個裝拆箱的操作呢?但是開發(fā)人員在調(diào)用處添加參數(shù),是不應該關心參數(shù)的數(shù)據(jù)類型才對,干脆數(shù)據(jù)類型參數(shù)不要了,改成如下方法了:
代碼如下:
public void AddParam(string ParaName, object ParaValue, DbParameterCollection ParaCollect)
{
if (ParaCollect.Count >= 1)
{
Para = (DbParameter)((ICloneable)ParaCollect[0]).Clone();
}
Para.ParameterName = string.Format(retParaformat, ParaName);//將參數(shù)格式化為具體的數(shù)據(jù)庫參數(shù)格式
if (ParaValue == null)
{
Para.Value = string.Empty;
}
else
{
Para.Value = ParaValue;
}
ParaCollect.Add(Para);
}
為了兼容不同的數(shù)據(jù)庫(主要是oracle變量特殊問題),添加參數(shù)的方法分兩種,一種是普通帶參執(zhí)行的DML語句,一種是代參執(zhí)行的存儲過程。對于SQL SERVER數(shù)據(jù)庫即使是存儲過程
變量參數(shù)仍是@前綴,ORACLE存儲過程又是什么前綴呢?很遺憾,ORACLE存儲過程的參數(shù)變量是不需要任何前綴的,為了單獨兼容這一點,對于不同數(shù)據(jù)庫如果調(diào)用的存儲過程有參數(shù)
的話,建議用下面的三個添加參數(shù)的方法:
代碼如下:
/// <summary>
/// 存儲過程輸入?yún)?shù)
/// </summary>
/// <param name="ParaName"></param>
/// <param name="ParaValue"></param>
/// <param name="ParaCollect"></param>
public void AddInputParam(string ParaName, object ParaValue, DbParameterCollection ParaCollect)
{
if (ParaCollect.Count >= 1)
{
Para = (DbParameter)((ICloneable)ParaCollect[0]).Clone();
}
Para.ParameterName = string.Format(retParaformat.Replace(":",""), ParaName);//ORACLE存儲過程參數(shù)前沒有冒號
if (ParaValue == null)
{
Para.Value = string.Empty;
}
else
{
Para.Value = ParaValue;
}
ParaCollect.Add(Para);
}
/// <summary>
/// 存儲過程
/// <summary>
/// 執(zhí)行SQL并返回數(shù)據(jù)集
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataSet ExecDataSet(string Sql)
{
DataSet ds = new DataSet();
try
{
this.Open();
cmd.CommandText = Replace(Sql);
Adapter.SelectCommand = cmd;
Adapter.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
return ds;
}
上面的方法大家看了是不是覺得既簡單又熟悉,確實是的,但仍然相當以前的xxhelper.cs里是做了簡化的,該方法既可以直接執(zhí)行不帶參DML語句,也可以執(zhí)行帶參的,但是該方法的形參卻
只有一個,之前的xxhelper.cs里帶參執(zhí)行的話,形參中大多至少還另外一個形參的,比如SqlPeremeters[]類型或參數(shù)集合類型的形參,而且方法體里面大多會循環(huán)讀取參數(shù),上面的方法里
卻沒有,都簡化掉了,唯一多了一點的是,所執(zhí)行的命令語句執(zhí)行前要做一個特殊字符替換,cmd.CommandText = Replace(Sql),Replace方法主要是替換參數(shù)前綴,Replace方法如下:
代碼如下:
/// <summary>
/// 替換DML語句里的參數(shù)前綴
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string Replace(string str)
{
return str.Replace("$", retParaformat.Substring(0, 1));
}
因為不同數(shù)據(jù)庫除了在添加參數(shù)時有前綴的區(qū)別,再具體執(zhí)行語句時也有前綴區(qū)別嘛,比如SQL SERVER里 SELECT USER_NAME,USER_AGE FROM USERS WHERE USER_ID=@USER_ID,ORACLE里是這樣的SELECT USER_NAME,USER_AGE FROM USERS WHERE USER_ID=:USER_ID,在此就需要統(tǒng)一一個前綴規(guī)則了,統(tǒng)一這樣SELECT USER_NAME,USER_AGE FROM USERS WHERE USER_ID=$USER_ID,在執(zhí)行前根據(jù)不同數(shù)據(jù)庫替換前綴$符號,當然這個約定規(guī)則不一定是最完美的,也許還存在一定的問題,寫到這我也突然想起來之前我見過別人
的系統(tǒng)中有的就是變量參數(shù)用的這種類似特殊符號,肯定也是為了兼容多數(shù)據(jù)庫所作的處理了,呵呵,具體的調(diào)用及測試之后統(tǒng)一說明。還有幾個方法也和上面類似,大家都熟悉的。如下(不再做具體解釋了):
代碼如下:
/// <summary>
/// 執(zhí)行SQL語句并返回DataReader對象
/// </summary>
/// <param name="dbcon"></param>
/// <param name="cmdText"></param>
/// <returns></returns>
public DbDataReader ExecuteDataReader(DbConnection dbcon,string cmdText)
{
try
{
if (dbcon.State == ConnectionState.Closed)
{
dbcon.Open();
}
cmd.CommandText = Replace(cmdText);
DbDataReader dr = cmd.ExecuteReader();
cmd.Parameters.Clear();
cmd.Dispose();
return dr;
}
catch
{
dbcon.Close();//發(fā)生異常在此處關閉,否則在調(diào)用顯式處關閉
return null;
}
}/// <summary>
/// 判斷記錄是否存在
/// </summary>
/// <param name="Sql"></param>
/// <returns></returns>
public bool Exist(string Sql)
{
bool exist;
this.Open();
cmd.CommandText = Replace(Sql);
DbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
exist = true; //記錄存在
}
else
{
exist = false; //記錄不存在
}
dr.Close();
this.Close();
return exist;
}
/// <summary>
/// 執(zhí)行SQL語句
/// </summary>
/// <param name="sql"></param>
public void ExecSql(string Sql)
{
try
{
this.Open();
cmd.CommandText = Replace(Sql);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}}
/// <summary>
/// 執(zhí)行SQL語句,返回一個單值
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public string ReturnValue(string Sql)
{
object returnValue = string.Empty;
try
{
this.Open();
cmd.CommandText = Replace(Sql);
returnValue = cmd.ExecuteScalar();
if (returnValue == null)
{
returnValue = string.Empty;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
return returnValue.ToString();
}
/// <summary>
/// 執(zhí)行多條SQL語句并啟用數(shù)據(jù)庫事務
/// </summary>
/// <param name="SQLStringList"></param>
public bool ExecSqlTran(List<String> SQLStringList)
{
this.Open();
DbTransaction trans = conn.BeginTransaction();
cmd.Transaction = trans;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
cmd.CommandText = Replace(SQLStringList[n]);
cmd.ExecuteNonQuery();
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
return false;
}
finally
{
this.Close();
}
}
下面說下兩個存儲過程,存儲過程基本上分兩種,返回結果集的存儲過程和執(zhí)行業(yè)務邏輯不返回結果集但卻有返回值(如標志等),對于需要有返回值的存儲過程,我個人趨向于用
代碼如下:
/// <summary>
/// 執(zhí)行存儲過程并返回結果集
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <returns>DataSet</returns>
public DataSet RunProcedure(string storedProcName)
{
DataSet ds = new DataSet();
try
{
this.Open();
cmd.CommandText = storedProcName;
cmd.CommandType = CommandType.StoredProcedure;
Adapter.SelectCommand = cmd;
//Adapter.SelectCommand.CommandTimeout = 1200;//可以設置適當?shù)某瑫r時間(秒),避免選擇時間段過大導致填充數(shù)據(jù)集超時
Adapter.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
return ds;
}
/// <summary>
/// 執(zhí)行存儲過程,方法不返回結果集
/// </summary>
/// <param name="storedProcName"></param>
public void RunVoidProcedure(string storedProcName)
{
cmd.CommandText = storedProcName;
cmd.CommandType = CommandType.StoredProcedure;
try
{
this.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
}
下面說兩個反射方法,測試之后為了方便調(diào)用,減少操作添加的,一個是把實體類的屬性轉換為參數(shù),另一個是把從數(shù)據(jù)庫取出的某條記錄轉換為實體類,這兩個還是非常有用,尤其是在系統(tǒng)開發(fā)時調(diào)用比較方便,以前我是見到反射就繞道走的,這次算是第一次用反射,發(fā)現(xiàn)確實是很方便。如下:
代碼如下:
/// <summary>
/// 將實體類的屬性進行參數(shù)轉換(ORACLE測試通不過,必須要求所有參數(shù)都包含在語句中才行)
/// </summary>
/// <param name="model"></param>
/// <param name="ParaCollect"></param>
//public void ConvertToParameters(object model, DbParameterCollection ParaCollect)
//{
// Type T = model.GetType();
// PropertyInfo[] propert = T.GetProperties();
// for (int i = 0; i < propert.Length; i++)
// {
// AddParam(propert[i].Name, propert[i].GetValue(model, null), ParaCollect);
// }
//}
/// <summary>
/// 將實體類的屬性進行參數(shù)轉換
/// </summary>
/// <param name="model"></param>
/// <param name="ParaCollect"></param>
public void ConvertToParameters(object model, DbParameterCollection ParaCollect,List<string> fields)
{
Type T = model.GetType();
PropertyInfo[] propert = T.GetProperties();
for (int i = 0; i < propert.Length; i++)
{
if (fields.Contains(propert[i].Name)) //檢測必須參數(shù)化的實體屬性
{
AddParam(propert[i].Name, propert[i].GetValue(model, null), ParaCollect);
}
}
}/// <summary>
/// 通過反射將取出的數(shù)據(jù)寫入實體類(ORACLE測試通不過,需進行類型強制轉換)
/// </summary>
/// <param name="model"></param>
/// <param name="cmdText"></param>
//public void GetModel(object model, string cmdText)
//{
// PropertyInfo propertyInfo;
// DbDataReader dr = ExecuteDataReader(conn, cmdText);
// while (dr.Read())
// {
// for (int i = 0; i < dr.FieldCount; i++)
// {
// propertyInfo = model.GetType().GetProperty(dr.GetName(i));
// if (propertyInfo != null)
// {
// if (dr.GetValue(i) != DBNull.Value)
// {
// //Type t = dr.GetValue(i).GetType();
// propertyInfo.SetValue(model, dr.GetValue(i), null);
// }
// }
// }
// }
// dr.Close();
// conn.Close();
//}
/// <summary>
/// 通過反射將數(shù)據(jù)綁定到實體對象,由于不同數(shù)據(jù)庫對應于.NET的數(shù)據(jù)類型不一樣
/// 需做強制類型轉換
/// </summary>
/// <param name="model"></param>
/// <param name="cmdText"></param>
public void GetModel(object model, string cmdText)
{
PropertyInfo propertyInfo;
DbDataReader dr = ExecuteDataReader(conn, cmdText);
object _value;
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
propertyInfo = model.GetType().GetProperty(dr.GetName(i));
if (propertyInfo != null && dr.GetValue(i) != DBNull.Value)
{
switch (propertyInfo.PropertyType.ToString())
{
case "System.String":
{
_value = Convert.ToString(dr.GetValue(i));//字符串是全球通用類型,也可以不用轉換
propertyInfo.SetValue(model, _value, null);
}break;
case "System.Int32":
{
_value = Convert.ToInt32(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "System.Single":
{
_value = Convert.ToSingle(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "System.Decimal":
{
_value = Convert.ToDecimal(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "System.Double":
{
_value = Convert.ToDouble(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "":
{
_value = Convert.ToDateTime(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
default: break;
}
}
}
}
dr.Close();
conn.Close();
}
從上面的注釋掉的方法對比中可以看到為了兼容不同的數(shù)據(jù)庫,必須要做額外的處理,比如類型轉換,SQL SERVER的int 對應ORALCE的number,UserInfo的字段屬性UserAge定義的是int類型,連接ORALCE時,.NET識別number類型為System.Decimal,把Decimal賦值給Int32當然是不行的,所以得做強制轉換才行。還有一點要注意下,就是將數(shù)據(jù)綁定到實體對象時,由于ORACLE堅持大寫標準和解析機制,如果屬性名和字段名大小寫不一致的話,propertyInfo = model.GetType().GetProperty(dr.GetName(i)) ,propertyInfo 始終是null值,比如SELECT UserName,UserAge FROM USER_TEST WHERE USERID=$USERID,SQL SERVER 執(zhí)行的時候調(diào)試可以看到dr.GetName(0)是UserName,dr.GetName(1)是UserAge,ORACLE執(zhí)行解析就變了,全是大寫了,變成了USERNAE,USERAGE,這么一來和找不到UserInfo類的屬性了,因為UserInfo類的屬性是 UserName,和UserAge,C#語言變量也是區(qū)分大小寫的嘛,當然就找不到了,所以propertyInfo就為null了,故在這里再次建議大家在數(shù)據(jù)庫設計和程序字段屬性設計時采用大寫標準(如果不涉及多數(shù)據(jù)庫當然也不需要這么做)。
最后說下測試調(diào)用代碼,首先webconfig配置里面這樣配置下,主要選取SQL SERVER和ORACLE做測試,畢竟這是.NET支持的兩個典型數(shù)據(jù)庫,要是把.NET所支持的所有書庫都測試一遍,那測試量可不小了,呵呵。代碼如下:
<connectionStrings>
<add name="ConnStr" connectionString="uid=sa;pwd=peace;database=TEST;server=." providerName="System.Data.SqlClient" />
<!--<add name="ConnStr" connectionString="server=.;data source=peace;user id=cct;password=cct;enlist=true" providerName="System.Data.OracleClient"/>-->
</connectionStrings>
protected void Page_Load(object sender, EventArgs e)
{
//測試DataReader,SQLSERVER和ORACLE都通過
//DataProviderFactory fac = new DataProviderFactory();
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddParam("USERID", 100, ParaCollect);
//DbDataReader dr = fac.ExecuteDataReader(fac.conn, "SELECT * FROM USER_TEST WHERE USERID=$USERID");
//while (dr.Read())
//{
// string a = dr[1].ToString();
//}
//fac.conn.Close();//在調(diào)用處顯示關閉//無參數(shù)DataSet測試 SQLSERVER和ORACLE都通過
//DataTable dt = fac.ExecDataSet("SELECT * FROM USER_TEST").Tables[0];
//帶參數(shù)DataSet測試 SQLSERVER和ORACLE都通過
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddParam("USERID", 100, ParaCollect);
//fac.AddParam("USERNAME", "局%", ParaCollect);//這里的參數(shù)名可以任意成其它,不一定非要和字段名相同(下同)
//DataTable dt = fac.ExecDataSet("SELECT * FROM USER_TEST WHERE USERNAME LIKE $USERNAME").Tables[0];
//DataTable dt = fac.ExecDataSet("SELECT * FROM USER_TEST WHERE USERID=$USERID OR USERNAME LIKE $USERNAME").Tables[0];//多參數(shù)測試
//單值測試(帶參數(shù)) SQLSERVER和ORACLE都通過
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddParam("USERID", 100, ParaCollect);
//string retValue = fac.ReturnValue("SELECT USERNAME FROM USER_TEST WHERE USERID=$USERID");
//帶參存儲過程測試返回結果集 SQLSERVER和ORACLE都通過
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddParam("StartDate", "2009-8-1", ParaCollect);
//fac.AddParam("EndDate", "2009-8-21", ParaCollect);
//DataTable dt = fac.RunProcedure("USP_GetMixedReport").Tables[0];//帶參數(shù)測試存儲過程的
//改進后帶參數(shù)測試存儲過程的輸出參數(shù)值和返回值的測試 SQLSERVER和ORACLE都通過
//int flag = 0, sign = 0, ret = 0;
//DataProviderFactory fac = new DataProviderFactory();
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddInputParam("USER_ACCOUNT", "admin", ParaCollect);
//fac.AddInputParam("USER_PWD", "68053af2923e00204c3ca7c6a3150cf7", ParaCollect);
//fac.AddOutputParam("FLAG", ParaCollect);
//fac.AddOutputParam("SIGN", ParaCollect);
//fac.AddReturnParam("RetValue", ParaCollect);
//fac.RunVoidProcedure("SP_ValideLogin");
//string prefix = fac.retParaformat.Replace(":","");//Oracle存儲過程參數(shù)前冒號移除掉
//flag = int.Parse(ParaCollect[string.Format(prefix,"FLAG")].Value.ToString());
//sign = int.Parse(ParaCollect[string.Format(prefix, "SIGN")].Value.ToString());
//ret = int.Parse(ParaCollect[string.Format(prefix, "RetValue")].Value.ToString());//存儲過程約定返回值必須是int型
//調(diào)用存儲過程測試 SQLSERVER和ORACLE都通通過
//DataProviderFactory fac = new DataProviderFactory();
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddInputParam("P_UserID", 7, ParaCollect);
//fac.AddInputParam("P_UserName", "peace", ParaCollect);
//fac.AddInputParam("P_UserAge", 100, ParaCollect);
//fac.RunVoidProcedure("PROC_USER_TEST_ADD");
//多條提交事務處理測試 SQLSERVER和ORACLE都通過
//List<string> SqlList = new List<string>();
//DataProviderFactory fac = new DataProviderFactory();
//DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddParam("UserName", "peaceli", ParaCollect);
//fac.AddParam("UserAge", 150, ParaCollect);
//SqlList.Add("INSERT INTO USER_TEST(UserName,UserAge) VALUES($UserName,$UserAge)");
//SqlList.Add("INSERT INTO USER_TEST(UserName,UserAge) VALUES($UserName,$UserAge)");
//SqlList.Add("INSERT INTO USER_TEST(UserName,UserAge) VALUES($UserName,$UserAge)");
//fac.ExecSqlTran(SqlList);
//插入操作參數(shù)測試(SQL SERVER) 通過
//UserInfo ui = new UserInfo();
//ui.UserName = "hello peace";
//ui.UserAge = 100;
//Addinn(ui);
//插入操作參數(shù)測試(Oracle) 通過
//UserInfo ui = new UserInfo();
//ui.USERID = 10;
//ui.USERNAME = "hello peace";
//ui.USERAGE = 120;
//Addin(ui);
//插入操作反射參數(shù)轉換測試 SQLSERVER和ORACLE都通過
//UserInfo ui = new UserInfo();
//ui.USERNAME = "peaceli";
//ui.USERAGE = 110;
//Add(ui);
//返回實體對象測試 SQLSERVER和ORACLE都通過
UserInfo ui = new UserInfo();
ui.USERID = 1;
GetInfo(ui);
}
//private void Addinn(UserInfo ui)
//{
// DataProviderFactory fac = new DataProviderFactory();
// DbParameterCollection ParaCollect = fac.GetParmCollection();
// fac.AddParam("@UserName", ui.UserName, ParaCollect);
// fac.AddParam("@UserAge", ui.UserAge, ParaCollect);
// fac.ExecSql("INSERT INTO USER_TEST(UserName,UserAge) VALUES(@UserName,@UserAge)");
//}
private void Addin(UserInfo ui)
{
DataProviderFactory fac = new DataProviderFactory();
DbParameterCollection ParaCollect = fac.GetParmCollection();
//fac.AddParam(":UserName", ui.UserName, ParaCollect);//給參數(shù)賦值時冒號可以不加,但有的版本可能必須加
//fac.AddParam(":UserAge", ui.UserAge, ParaCollect);
//fac.AddParam("UserID", ui.USERID, ParaCollect); //這行注釋放開在ORACLE下同不過,ORACLE要求所全參數(shù)匹配,有多余參數(shù)就不行,這點有些變態(tài)
fac.AddParam("UserName", ui.USERNAME, ParaCollect);//SQL SERVER只要求用到的參數(shù)包含在參數(shù)集合里就行了,其它多余參數(shù)并不影響執(zhí)行
fac.AddParam("UserAge", ui.USERAGE, ParaCollect);
fac.ExecSql("INSERT INTO USER_TEST(UserName,UserAge) VALUES(:UserName,:UserAge)");
}
private void Add(UserInfo ui)
{
DataProviderFactory fac = new DataProviderFactory();
DbParameterCollection ParaCollect = fac.GetParmCollection();
string[] fields = { "USERNAME", "USERAGE" };//要求參數(shù)化的實體屬性
List<string> ListFields = new List<string>(fields);
fac.ConvertToParameters(ui, ParaCollect, ListFields);//如果新增記錄有很多參數(shù)的話,可能AddParam很多次,采用反射批量轉換
fac.ExecSql("INSERT INTO USER_TEST(USERNAME,USERAGE) VALUES($USERNAME,$USERAGE)");
}
private void GetInfo(UserInfo ui)
{
DataProviderFactory fac = new DataProviderFactory();
DbParameterCollection ParaCollect = fac.GetParmCollection();
fac.AddParam("USERID", ui.USERID, ParaCollect);
fac.GetModel(ui, "SELECT USERNAME,USERAGE FROM USER_TEST WHERE USERID=$USERID");
}
}
UserInfo類如下:
代碼如下:
public class UserInfo
{
public int USERID { get; set; }
public string USERNAME { get; set; }
public int USERAGE { get; set; }
}
測試到最后類屬性改動過,統(tǒng)一改成了大寫,再次建議大寫標準(包括數(shù)據(jù)庫設計),可以定義成USER_ID,USER_NAME,USER_AGE等,并與數(shù)據(jù)庫字段名保持一致,這樣有利于多數(shù)據(jù)庫的
兼容。
結語:個人并不反對項目里單獨用對應的xxhelper.cs,某個項目用SQLSERVER數(shù)據(jù)庫,就用SqlHelper.csL類,ORACLE就用OracleHelper.cs類,這樣來得更干脆快捷,基本上每個項目都是這對特定的數(shù)據(jù)庫在開發(fā),沒必要搞成通用類,真要搞成通用類,要經(jīng)過大量的實際測試,也許我最近有時寂寞空虛也無聊,突然想測試下同時也想改進下,呵呵,零零碎碎花了點時間測試了下,選取兩個數(shù)據(jù)庫測試了一遍,最終只需要改動config配置的數(shù)據(jù)庫連接就可以了,真正達到了一套系統(tǒng)的無縫切換。里面有些可能還說的不夠準確,可能也還有遺漏的地方,僅供參考吧?。?!
訪問類庫的文件完整的貼一次,如下:代碼如下:
//*****************************************************************************************************************
//* 編寫人 :peace
//* EMAIL : peacechzh@126.com
//* 開發(fā)日期:2009-10-21
//* 修 改 人:
//* 修改日期:
//* 描 述:數(shù)據(jù)庫工廠訪問類
//* 更新描述:里面供調(diào)用執(zhí)行的各方法可帶參數(shù)執(zhí)行,在外部指定參數(shù)名和參數(shù)值即可。
//* 最終期望:支持.NET所支持的所有數(shù)據(jù)庫并達到系統(tǒng)的無縫切換(盡情的忽悠吧O(∩_∩)O~)
//*****************************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Reflection;
namespace DataProvider
{
public class DataProviderFactory
{
public DbConnection conn;//抽象類型
private DbCommand cmd;//抽象類型
private DbProviderFactory provider;
private DbParameter Para;//不同數(shù)據(jù)庫參數(shù)類型的抽象類型
private DbDataAdapter Adapter;//對應不同數(shù)據(jù)庫的數(shù)據(jù)適配器
Dictionary<Type, String> ParametersFormat;//不同數(shù)據(jù)庫參數(shù)格式化類型
public string retParaformat = string.Empty;//最終返回的格式化標志,如@{0},:{0}
public DataProviderFactory()
{
//從配置文件中取出標示數(shù)據(jù)庫類型的字符串并通過ProviderName的不同支持不同類型的數(shù)據(jù)庫
string providerName = ConfigurationManager.ConnectionStrings["ConnStr"].ProviderName;//也可以用索引,從1開始
//創(chuàng)建一個數(shù)據(jù)庫對應的實例,使用該實例就可以創(chuàng)建對應的connection,command 和adapater等等對象
provider = DbProviderFactories.GetFactory(providerName);
//創(chuàng)建具體的數(shù)據(jù)庫連接類型和命令執(zhí)行類型
conn = provider.CreateConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
cmd = provider.CreateCommand();
cmd.Connection = conn;
//創(chuàng)建具體的參數(shù)類型
Para = provider.CreateParameter();
//創(chuàng)建具體的適配器類型
Adapter = provider.CreateDataAdapter();
//不同數(shù)據(jù)庫參數(shù)前綴格式化
ParametersFormat = new Dictionary<Type, String>();
ParametersFormat.Add(typeof(System.Data.SqlClient.SqlCommand), "@{0}");//因SQL SERVER只返回{0}沒有@前綴,在此初始化處理
//返回格式化標志
retParaformat = GetParameterFormat(cmd);
}
/// <summary>
/// 添加參數(shù)
/// </summary>
/// <param name="ParaName">參數(shù)名稱</param>
/// <param name="SqlType">參數(shù)數(shù)據(jù)類型</param>
/// <param name="ParaValue">參數(shù)值</param>
/// <param name="ParaCollect">參數(shù)對象的集合</param>
public void AddParam(string ParaName, DbType SqlType, object ParaValue, DbParameterCollection ParaCollect)
{
//不允許將一個DbCommand對象的Parameters插入到另外一個DbCommand對象,那么多個參數(shù)的話可以加上下面一句判斷
//如果已經(jīng)存在至少一個對象時,再深層拷貝一個
if (ParaCollect.Count >= 1)
{
Para = (DbParameter)((ICloneable)ParaCollect[0]).Clone();
}
Para.ParameterName = string.Format(retParaformat, ParaName);
Para.DbType = SqlType;
if (ParaValue == null)
{
Para.Value = string.Empty;//DBNull.Value;
}
else
{
Para.Value = ParaValue;
}
ParaCollect.Add(Para);
}
public void AddParam(string ParaName, object ParaValue, DbParameterCollection ParaCollect)
{
if (ParaCollect.Count >= 1)
{
Para = (DbParameter)((ICloneable)ParaCollect[0]).Clone();
}
Para.ParameterName = string.Format(retParaformat, ParaName);//將參數(shù)格式化為具體的數(shù)據(jù)庫參數(shù)格式
if (ParaValue == null)
{
Para.Value = string.Empty;
}
else
{
Para.Value = ParaValue;
}
ParaCollect.Add(Para);
}
/// <summary>
/// 存儲過程輸入?yún)?shù)
/// </summary>
/// <param name="ParaName"></param>
/// <param name="ParaValue"></param>
/// <param name="ParaCollect"></param>
public void AddInputParam(string ParaName, object ParaValue, DbParameterCollection ParaCollect)
{
if (ParaCollect.Count >= 1)
{
Para = (DbParameter)((ICloneable)ParaCollect[0]).Clone();
}
Para.ParameterName = string.Format(retParaformat.Replace(":",""), ParaName);//ORACLE存儲過程參數(shù)前沒有冒號
if (ParaValue == null)
{
Para.Value = string.Empty;
}
else
{
Para.Value = ParaValue;
}
ParaCollect.Add(Para);
}
/// <summary>
/// 存儲過程
/// <summary>
/// 判斷記錄是否存在
/// </summary>
/// <param name="Sql"></param>
/// <returns></returns>
public bool Exist(string Sql)
{
bool exist;
this.Open();
cmd.CommandText = Replace(Sql);
DbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
exist = true; //記錄存在
}
else
{
exist = false; //記錄不存在
}
dr.Close();
this.Close();
return exist;
}
/// <summary>
/// 執(zhí)行SQL語句
/// </summary>
/// <param name="sql"></param>
public void ExecSql(string Sql)
{
try
{
this.Open();
cmd.CommandText = Replace(Sql);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
}
/// <summary>
/// 執(zhí)行SQL語句,返回一個單值
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public string ReturnValue(string Sql)
{
object returnValue = string.Empty;
try
{
this.Open();
cmd.CommandText = Replace(Sql);
returnValue = cmd.ExecuteScalar();
if (returnValue == null)
{
returnValue = string.Empty;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
return returnValue.ToString();
}
/// <summary>
/// 執(zhí)行多條SQL語句并啟用數(shù)據(jù)庫事務
/// </summary>
/// <param name="SQLStringList"></param>
public bool ExecSqlTran(List<String> SQLStringList)
{
this.Open();
DbTransaction trans = conn.BeginTransaction();
cmd.Transaction = trans;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
cmd.CommandText = Replace(SQLStringList[n]);
cmd.ExecuteNonQuery();
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
return false;
}
finally
{
this.Close();
}
}
/// <summary>
/// 執(zhí)行存儲過程并返回結果集
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <returns>DataSet</returns>
public DataSet RunProcedure(string storedProcName)
{
DataSet ds = new DataSet();
try
{
this.Open();
cmd.CommandText = storedProcName;
cmd.CommandType = CommandType.StoredProcedure;
Adapter.SelectCommand = cmd;
//Adapter.SelectCommand.CommandTimeout = 1200;//可以設置適當?shù)某瑫r時間(秒),避免選擇時間段過大導致填充數(shù)據(jù)集超時
Adapter.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
return ds;
}
/// <summary>
/// 執(zhí)行存儲過程,方法不返回結果集
/// </summary>
/// <param name="storedProcName"></param>
public void RunVoidProcedure(string storedProcName)
{
cmd.CommandText = storedProcName;
cmd.CommandType = CommandType.StoredProcedure;
try
{
this.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.Close();
}
}
/// <summary>
/// 將實體類的屬性進行參數(shù)轉換(ORACLE測試通不過,必須要求所有參數(shù)都包含在語句中才行)
/// </summary>
/// <param name="model"></param>
/// <param name="ParaCollect"></param>
//public void ConvertToParameters(object model, DbParameterCollection ParaCollect)
//{
// Type T = model.GetType();
// PropertyInfo[] propert = T.GetProperties();
// for (int i = 0; i < propert.Length; i++)
// {
// AddParam(propert[i].Name, propert[i].GetValue(model, null), ParaCollect);
// }
//}
/// <summary>
/// 將實體類的屬性進行參數(shù)轉換
/// </summary>
/// <param name="model"></param>
/// <param name="ParaCollect"></param>
public void ConvertToParameters(object model, DbParameterCollection ParaCollect,List<string> fields)
{
Type T = model.GetType();
PropertyInfo[] propert = T.GetProperties();
for (int i = 0; i < propert.Length; i++)
{
if (fields.Contains(propert[i].Name)) //檢測必須參數(shù)化的實體屬性
{
AddParam(propert[i].Name, propert[i].GetValue(model, null), ParaCollect);
}
}
}
/// <summary>
/// 通過反射將取出的數(shù)據(jù)寫入實體類(ORACLE測試通不過,需進行類型強制轉換)
/// </summary>
/// <param name="model"></param>
/// <param name="cmdText"></param>
//public void GetModel(object model, string cmdText)
//{
// PropertyInfo propertyInfo;
// DbDataReader dr = ExecuteDataReader(conn, cmdText);
// while (dr.Read())
// {
// for (int i = 0; i < dr.FieldCount; i++)
// {
// propertyInfo = model.GetType().GetProperty(dr.GetName(i));
// if (propertyInfo != null)
// {
// if (dr.GetValue(i) != DBNull.Value)
// {
// //Type t = dr.GetValue(i).GetType();
// propertyInfo.SetValue(model, dr.GetValue(i), null);
// }
// }
// }
// }
// dr.Close();
// conn.Close();
//}
/// <summary>
/// 通過反射將數(shù)據(jù)綁定到實體對象,由于不同數(shù)據(jù)庫對應于.NET的數(shù)據(jù)類型不一樣
/// 需做強制類型轉換
/// </summary>
/// <param name="model"></param>
/// <param name="cmdText"></param>
public void GetModel(object model, string cmdText)
{
PropertyInfo propertyInfo;
DbDataReader dr = ExecuteDataReader(conn, cmdText);
object _value;
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
propertyInfo = model.GetType().GetProperty(dr.GetName(i));
if (propertyInfo != null && dr.GetValue(i) != DBNull.Value)
{
switch (propertyInfo.PropertyType.ToString())
{
case "System.String":
{
_value = Convert.ToString(dr.GetValue(i));//字符串是全球通用類型,也可以不用轉換
propertyInfo.SetValue(model, _value, null);
}break;
case "System.Int32":
{
_value = Convert.ToInt32(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "System.Single":
{
_value = Convert.ToSingle(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "System.Decimal":
{
_value = Convert.ToDecimal(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "System.Double":
{
_value = Convert.ToDouble(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
case "":
{
_value = Convert.ToDateTime(dr.GetValue(i));
propertyInfo.SetValue(model, _value, null);
} break;
default: break;
}
}
}
}
dr.Close();
conn.Close();
}
/// <summary>
/// 根據(jù)不同的數(shù)據(jù)庫命令對象返回該類型數(shù)據(jù)庫參數(shù)的前綴格式化字符串
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
private string GetParameterFormat(DbCommand command)
{
if (!ParametersFormat.ContainsKey(command.GetType()))
{
this.Open();//讀取參數(shù)前綴時需打開數(shù)據(jù)庫連接
ParametersFormat.Add(
command.GetType(),
command.Connection.GetSchema("DataSourceInformation")
.Rows[0]["ParameterMarkerFormat"].ToString());
//conn.Close();在真正執(zhí)行語句的時候去關閉,避免重復打開
}
return ParametersFormat[command.GetType()];
}
private void Open()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
private void Close()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
/// <summary>
/// 替換DML語句里的參數(shù)前綴
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string Replace(string str)
{
return str.Replace("$", retParaformat.Substring(0, 1));
}
}
}
文件下載:PeaceHelper.cs
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com