Enterprise Library 2.0很多人都已熟悉,有的人也在很多項目裡做了應用,
很早以前也使用企業庫的2.0做了一些項目,但感覺很多代碼還是有些冗余和重複,
同時為了兼容現有的系統結構而不影響現有數據訪問方式(包括代碼生成器的DAL代碼)不變,
對Enterprise Library 2.0 的調用進行了進一步封裝(按我過去DbHelperSQL的思路),在不改變現有的DAL的方式下來使用企業庫。
當然,你完全可以直接使用企業庫做一些更靈活的應用,這裡只是拋磚引玉的一個解決方案。
/// <summary>
/// Enterprise Library 2.0 數據訪問進一步封裝類
/// Copyright (C) 2006-2008 LiTianPing
/// All rights reserved
/// </summary>
public abstract class DbHelperSQL2
{
public DbHelperSQL2()
{
}
#region 公用方法
/// <summary>
/// 獲取表某個字段的最大值
/// </summary>
/// <param name="FieldName"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static int GetMaxID(string FieldName,string TableName)
{
string strSql = "select max(" + FieldName + ")+1 from " + TableName;
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
object obj = db.ExecuteScalar(dbCommand);
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <summary>
/// 檢測一個記錄是否存在(SQL語句方式)
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public static bool Exists(string strSql)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
object obj = db.ExecuteScalar(dbCommand);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 檢測一個記錄是否存在(SqlParameter語句方式)
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params SqlParameter[] cmdParms)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
BuildDBParameter(db, dbCommand, cmdParms);
object obj = db.ExecuteScalar(dbCommand);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 加載參數
/// </summary>
public static void BuildDBParameter(Database db, DbCommand dbCommand, params SqlParameter[] cmdParms)
{
foreach (SqlParameter sp in cmdParms)
{
db.AddInParameter(dbCommand, sp.ParameterName, sp.DbType,sp.Value);
}
}
#endregion
#region 執行簡單SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="strSql">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string strSql)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
return db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// 執行SQL語句,返回影響的記錄數(對於長時間查詢的語句,設置等待時間避免查詢超時)
/// </summary>
/// <param name="strSql"></param>
/// <param name="Times"></param>
/// <returns></returns>
public static int ExecuteSqlByTime(string strSql,int Times)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
dbCommand.CommandTimeout = Times;
return db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
Database db = DatabaseFactory.CreateDatabase();
using (DbConnection dbconn = db.CreateConnection())
{
dbconn.Open();
DbTransaction dbtran = dbconn.BeginTransaction();
try
{
//執行語句
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
DbCommand dbCommand = db.GetSqlStringCommand(strsql);
db.ExecuteNonQuery(dbCommand);
}
}
//執行存儲過程
//db.ExecuteNonQuery(CommandType.StoredProcedure, "InserOrders");
//db.ExecuteDataSet(CommandType.StoredProcedure, "UpdateProducts");
dbtran.Commit();
}
catch
{
dbtran.Rollback();
}
finally
{
dbconn.Close();
}
}
}
#region 執行一個特殊字段帶參數的語句
/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="strSql">SQL語句</param>
/// <param name="content">參數內容,比如一個字段是格式複雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string strSql,string content)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
db.AddInParameter(dbCommand, "@content", DbType.String, content);
return db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="strSql">SQL語句</param>
/// <param name="content">參數內容,比如一個字段是格式複雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>返回語句裡的查詢結果</returns>
public static object ExecuteSqlGet(string strSql,string content)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
db.AddInParameter(dbCommand, "@content", DbType.String, content);
object obj = db.ExecuteNonQuery(dbCommand);
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
/// <summary>
/// 向數據庫裡插入圖像格式的字段(和上面情況類似的另一種實例)
/// </summary>
/// <param name="strSql">SQL語句</param>
/// <param name="fs">圖像字節,數據庫的字段類型為image的情況</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSqlInsertImg(string strSql,byte[] fs)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
db.AddInParameter(dbCommand, "@fs", DbType.Byte, fs);
return db.ExecuteNonQuery(dbCommand);
}
#endregion
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="strSql">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string strSql)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
object obj = db.ExecuteScalar(dbCommand);
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
/// <summary>
/// 執行查詢語句,返回SqlDataReader ( 注意:使用後一定要對SqlDataReader進行Close )
/// </summary>
/// <param name="strSql">查詢語句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSql)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
SqlDataReader dr = (SqlDataReader)db.ExecuteReader(dbCommand);
return dr;
}
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="strSql">查詢語句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string strSql)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
return db.ExecuteDataSet(dbCommand);
}
//(對於長時間查詢的語句,設置等待時間避免查詢超時)
public static DataSet Query(string strSql,int Times)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
dbCommand.CommandTimeout = Times;
return db.ExecuteDataSet(dbCommand);
}
#endregion
#region 執行帶參數的SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="strSql">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string strSql,params SqlParameter[] cmdParms)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
BuildDBParameter(db, dbCommand, cmdParms);
return db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的哈希表(key為sql語句,value是該語句的SqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
Database db = DatabaseFactory.CreateDatabase();
using (DbConnection dbconn = db.CreateConnection())
{
dbconn.Open();
DbTransaction dbtran = dbconn.BeginTransaction();
try
{
//執行語句
foreach (DictionaryEntry myDE in SQLStringList)
{
string strsql = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
if (strsql.Trim().Length > 1)
{
DbCommand dbCommand = db.GetSqlStringCommand(strsql);
BuildDBParameter(db, dbCommand, cmdParms);
db.ExecuteNonQuery(dbCommand);
}
}
dbtran.Commit();
}
catch
{
dbtran.Rollback();
}
finally
{
dbconn.Close();
}
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="strSql">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string strSql,params SqlParameter[] cmdParms)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
BuildDBParameter(db, dbCommand, cmdParms);
object obj = db.ExecuteScalar(dbCommand);
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
/// <summary>
/// 執行查詢語句,返回SqlDataReader ( 注意:使用後一定要對SqlDataReader進行Close )
/// </summary>
/// <param name="strSql">查詢語句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSql,params SqlParameter[] cmdParms)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
BuildDBParameter(db, dbCommand, cmdParms);
SqlDataReader dr = (SqlDataReader)db.ExecuteReader(dbCommand);
return dr;
}
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="strSql">查詢語句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string strSql,params SqlParameter[] cmdParms)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(strSql);
BuildDBParameter(db, dbCommand, cmdParms);
return db.ExecuteDataSet(dbCommand);
}
private static void PrepareCommand(SqlCommand cmd,SqlConnection conn,SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ( ( parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input ) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
#endregion
#region 存儲過程操作
/// <summary>
/// 執行存儲過程,返回影響的行數
/// </summary>
public static int RunProcedure(string storedProcName)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand(storedProcName);
return db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// 執行存儲過程,返回輸出參數的值和影響的行數
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <param name="OutParameter">輸出參數名稱</param>
/// <param name="rowsAffected">影響的行數</param>
/// <returns></returns>
public static object RunProcedure(string storedProcName, IDataParameter[] InParameters, SqlParameter OutParameter, int rowsAffected)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand(storedProcName);
BuildDBParameter(db, dbCommand, (SqlParameter[])InParameters);
db.AddOutParameter(dbCommand, OutParameter.ParameterName, OutParameter.DbType, OutParameter.Size);
rowsAffected = db.ExecuteNonQuery(dbCommand);
return db.GetParameterValue(dbCommand,"@" + OutParameter.ParameterName); //得到輸出參數的值
}
/// <summary>
/// 執行存儲過程,返回SqlDataReader ( 注意:使用後一定要對SqlDataReader進行Close )
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters )
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand(storedProcName, parameters);
//BuildDBParameter(db, dbCommand, parameters);
return (SqlDataReader)db.ExecuteReader(dbCommand);
}
/// <summary>
/// 執行存儲過程,返回DataSet
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <param name="tableName">DataSet結果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName )
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand(storedProcName, parameters);
//BuildDBParameter(db, dbCommand, parameters);
return db.ExecuteDataSet(dbCommand);
}
/// <summary>
/// 執行存儲過程,返回DataSet(設定等待時間)
/// </summary>
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName ,int Times)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand(storedProcName, parameters);
dbCommand.CommandTimeout = Times;
//BuildDBParameter(db, dbCommand, parameters);
return db.ExecuteDataSet(dbCommand);
}
/// <summary>
/// 構建SqlCommand 對像(用來返回一個結果集,而不是一個整數值)
/// </summary>
/// <param name="connection">數據庫連接</param>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection,string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand( storedProcName, connection );
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
if( parameter != null )
{
// 檢查未分配值的輸出參數,將其分配以DBNull.Value.
if ( ( parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input ) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
return command;
}
/// <summary>
/// 創建SqlCommand 對像實例(用來返回一個整數值)
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <returns>SqlCommand 對像實例</returns>
private static SqlCommand BuildIntCommand(SqlConnection connection,string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection,storedProcName, parameters );
command.Parameters.Add( new SqlParameter ( "ReturnValue",
SqlDbType.Int,4,ParameterDirection.ReturnValue,
false,0,0,string.Empty,DataRowVersion.Default,null ));
return command;
}
#endregion
}
對使用現有Codematic代碼生成的用戶想使用企業庫的話,可以直接替換此類。
同時,對於直接對企業庫的DAL代碼生成,希望在以後有時間會加進去,以方便大家不同方式的開發。(李天平)
留言列表