一個資料庫操作類的執行個體(二.Provider類)
來源:互聯網
上載者:User
資料|資料庫 using System;
namespace com.joybase.DB
{
/// <summary>
/// 資料庫連接提供類
/// </summary>
public class Provider
{
//一個靜態串連介面;
private static System.Data.IDbConnection conn;
/// <summary>
/// 構造方法,設為私人類型,是防止外部無效的引用;
/// </summary>
protected Provider()
{
//
// TODO: Add constructor logic here
//
System.Data.IDbCommand x=new System.Data.OleDb.OleDbCommand();
}
// /// <summary>
// /// 資料庫連接類型,即判斷是System.Data.SqlClient類型或者是System.Data.OleDB類型的。
// /// </summary>
// private static DBType DataBaseType
// {
// get
// {
// //從設定檔當中讀取資料庫類型字串
// string m_DBType=System.Configuration.ConfigurationSettings.AppSettings["DataBase.Type"];
// //如果未設定預設為System.Data.SqlClient類型的串連
// if(m_DBType==null)
// {
// return DBType.SqlClient;
// }
// else
// {
// //如果為空白或者為MSSQLServer2000,則使用System.Data.SqlClient類型的串連
// if(m_DBType.Trim()==""||m_DBType.Trim().ToUpper()=="MSSQLSERVER2000"||m_DBType.Trim().ToUpper()=="MSSQLSERVER7")
// {
// return DBType.SqlClient;
// }
// //其它則返回System.Data.OleDB類型的串連
// else
// {
// if(m_DBType.Trim().ToUpper()=="OLEDB")
// {
// return DBType.OleDB;
// }
// }
//
// }
// return DBType.OleDB;
//
// }
//
//
// }
/// <summary>
/// 重載getConn(string)方法,此時連接字串的標籤名將為“DataBase.ConnectionString”
/// <seealso cref="getConn(string) "/>
/// </summary>
/// <returns>返回一個串連</returns>
public static System.Data.IDbConnection getConn()
{
return Provider.getConn("");
}
/// <summary>
/// 獲得資料庫連接介面
/// </summary>
/// <param name="p_ConnStringSetName">一個在Config檔案中設定連接字串的標籤名</param>
/// <returns></returns>
public static System.Data.IDbConnection getConn(string p_ConnStringSetName)
{
// if(conn==null)
// {
string ConnStr="";
if(p_ConnStringSetName.Trim()=="")
{
ConnStr=System.Configuration.ConfigurationSettings.AppSettings["DataBase.ConnectionString"];
}
else
{
ConnStr=System.Configuration.ConfigurationSettings.AppSettings[p_ConnStringSetName];
}
if(ConnStr==null||ConnStr=="")
{
throw new Exception("Not find connection string!");
}
DBType m_DBType;//=Provider.DataBaseType;
/*
* 注釋:我們對前面的編碼進行了部分的修改,鑒於System.Data.SqlClient的串連
* 字串當中不可能出現"Provider"字樣,所以我們根據是否有Provider字樣來判斷
* 該串連是基於System.Data.SqlClient的或者System.Data.OleDB的。
* 參考資料:
* 可以將 ConnectionString 屬性設定為單個單元。(不能為 SqlConnection 對象指定 Provider 屬性。)
* –或–
*
* 可以設定單個屬性(DataSource、Database、UserName 等等)。如果設定單個屬性,則將為您產生連接字串。
* 注意 在連接字串中儲存使用者名稱和密碼有安全性設定的意味。有關詳細資料,請參閱Introduction to ADO.NET Connection Design Tools。
*
*/
if(ConnStr.ToLower().IndexOf("provider")==-1) m_DBType=DBType.SqlClient;
else m_DBType=DBType.OleDB;
try
{
if(m_DBType==DBType.SqlClient)
{
conn=new System.Data.SqlClient.SqlConnection(ConnStr);
}
else
{
conn=new System.Data.OleDb.OleDbConnection(ConnStr);
}
}
catch
{
throw new Exception("Error to connect DB!");
}
// }
//if(conn.State!=System.Data.ConnectionState.Closed) conn.Close();
return conn;
}
}
/// <summary>
/// 枚舉類型,即一個資料庫連接類型的枚舉
/// </summary>
enum DBType
{
SqlClient=0,
OleDB=1
}
}