轉自http://blog.csdn.net/allen3010/article/details/6336717
這個是針對ACCESS資料庫操作的類,同樣也是從SQLHELPER提取而來,分頁程式的呼叫可以參考MSSQL那個類的呼叫,差不多的,只是提取所有記錄的數量的時候有多一個引數,這個需要注意一下!
c# 程式碼
using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
namespace NMJU.Web.DBUtility
{ /// <summary>
/// 資料訪問抽象基礎類(ACCESS)
/// Copyright (C) 2006-2007 NMJU.NET
/// All rights reserved
/// </summary>
public abstract class DbHelperACE
{
//資料庫連線字串(web.config來配置)
//public static string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
// public static string connectionString = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["AccessConnectionString"]);
public static string connectionString = ConfigurationManager.AppSettings["AccessConnectionString"];
public DbHelperACE()
{
}
#region 公用方法
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = DbHelperACE.GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public static bool Exists(string strSql)
{
object obj = DbHelperACE.GetSingle(strSql);
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;
}
}
public static bool Exists(string strSql, params OleDbParameter[] cmdParms)
{
object obj = DbHelperACE.GetSingle(strSql, cmdParms);
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;
}
}
#endregion
#region 執行簡單SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 執行SQL語句,設定命令的執行等待時間
/// </summary>
/// <param name="SQLString"></param>
/// <param name="Times"></param>
/// <returns></returns>
public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.OleDb.OleDbException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
/// <summary>
/// 向資料庫裡插入影象格式的欄位(和上面情況類似的另一種例項)
/// </summary>
/// <param name="strSQL">SQL語句</param>
/// <param name="fs">影象位元組,資料庫的欄位型別為image的情況</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
System.Data.OleDb.OleDbParameter myParameter = new System.Data.OleDb.OleDbParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string SQLString)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.OleDb.OleDbException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 執行查詢語句,返回SqlDataReader(使用該方法切記要手工關閉SqlDataReader和連線)
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>SqlDataReader</returns>
public static OleDbDataReader ExecuteReader(string strSQL)
{
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
try
{
connection.Open();
OleDbDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
//finally //不能在此關閉,否則,返回的物件將無法使用
//{
// cmd.Dispose();
// connection.Close();
//}
}
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.OleDb.OleDbException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
/// <summary>
/// 執行查詢語句,返回DataSet,設定命令的執行等待時間
/// </summary>
/// <param name="SQLString"></param>
/// <param name="Times"></param>
/// <returns></returns>
public static DataSet Query(string SQLString, int Times)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (System.Data.OleDb.OleDbException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region 執行帶引數的SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的雜湊表(key為sql語句,value是該語句的OleDbParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbTransaction trans = conn.BeginTransaction())
{
OleDbCommand cmd = new OleDbCommand();
try
{
//迴圈
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
OleDbParameter[] cmdParms = (OleDbParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
trans.Commit();
}
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 執行查詢語句,返回SqlDataReader (使用該方法切記要手工關閉SqlDataReader和連線)
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>SqlDataReader</returns>
public static OleDbDataReader ExecuteReader(string SQLString, params OleDbParameter[] cmdParms)
{
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
OleDbDataReader myReader = cmd.ExecuteReader();
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
//finally //不能在此關閉,否則,返回的物件將無法使用
//{
// cmd.Dispose();
// connection.Close();
//}
}
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.OleDb.OleDbException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, string cmdText, OleDbParameter[] 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 (OleDbParameter 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>
/// <param name="_tbName">----要顯示的表或多個表的連線</param>
/// <param name="_ID">----主表的主鍵</param>
/// <param name="_strCondition">----查詢條件,不需where</param>
/// <param name="_Dist">----是否新增查詢欄位的 DISTINCT 預設0不新增/1新增</param>
/// <returns></returns>
public static string getPageListCounts(string _ID, string _tbName, string _strCondition, int _Dist)
{
//---存放取得查詢結果總數的查詢語句
//---對含有DISTINCT的查詢進行SQL構造
//---對含有DISTINCT的總數查詢進行SQL構造
string strTmp = "", SqlSelect = "", SqlCounts = "";
if (_Dist == 0)
{
SqlSelect = "Select ";
SqlCounts = "COUNT(*)";
}
else
{
SqlSelect = "Select DISTINCT ";
SqlCounts = "COUNT(DISTINCT " + _ID + ")";
}
if (_strCondition == string.Empty)
{
strTmp = SqlSelect + " "+ SqlCounts + " FROM " + _tbName;
}
else
{
strTmp = SqlSelect + " "+ SqlCounts + " FROM " + " Where (1=1) " + _strCondition;
}
return strTmp;
}
/// <summary>
/// 智慧返回SQL語句
/// </summary>
/// <param name="primaryKey">主鍵(不能為空)</param>
/// <param name="queryFields">提取欄位(不能為空)</param>
/// <param name="tableName">表(理論上允許多表)</param>
/// <param name="condition">條件(可以空)</param>
/// <param name="OrderBy">排序,格式:欄位名+""+ASC(可以空)</param>
/// <param name="pageSize">分頁數(不能為空)</param>
/// <param name="pageIndex">當前頁,起始為:1(不能為空)</param>
/// <returns></returns>
public static string getPageListSql(string primaryKey, string queryFields, string tableName, string condition, string orderBy, int pageSize, int pageIndex)
{
string strTmp = ""; //---strTmp用於返回的SQL語句
string SqlSelect = "", SqlPrimaryKeySelect = "", strOrderBy = "", strWhere = " where 1=1 ", strTop = "";
//0:分頁數量
//1:提取欄位
//2:表
//3:條件
//4:主鍵不存在的記錄
//5:排序
SqlSelect = " select top {0} {1} from {2} {3} {4} {5}";
//0:主鍵
//1:TOP數量,為分頁數*(排序號-1)
//2:表
//3:條件
//4:排序
SqlPrimaryKeySelect = " and {0} not in (select {1} {0} from {2} {3} {4}) ";
if (orderBy != "")
strOrderBy = " order by " + orderBy;
if (condition != "")
strWhere += " and " + condition;
int pageindexsize = (pageIndex - 1) * pageSize;
if (pageindexsize > 0)
{
strTop = " top " + pageindexsize.ToString();
SqlPrimaryKeySelect = String.Format(SqlPrimaryKeySelect, primaryKey, strTop, tableName, strWhere, strOrderBy);
strTmp = String.Format(SqlSelect, pageSize.ToString(), queryFields, tableName, strWhere, SqlPrimaryKeySelect, strOrderBy);
}
else
{
strTmp = String.Format(SqlSelect, pageSize.ToString(), queryFields, tableName, strWhere, "", strOrderBy);
}
return strTmp;
}
/// <summary>
/// 獲取根據指定欄位排序並分頁查詢。DataSet
/// </summary>
/// <param name="pageSize">每頁要顯示的記錄的數目</param>
/// <param name="pageIndex">要顯示的頁的索引</param>
/// <param name="tableName">要查詢的資料表</param>
/// <param name="queryFields">要查詢的欄位,如果是全部欄位請填寫:*</param>
/// <param name="primaryKey">主鍵欄位,類似排序用到</param>
/// <param name="orderBy">是否為升序排列:0為升序,1為降序</param>
/// <param name="condition">查詢的篩選條件</param>
/// <returns>返回排序並分頁查詢的DataSet</returns>
public static DataSet GetPagingList(string primaryKey, string queryFields, string tableName, string condition, string orderBy, int pageSize, int pageIndex)
{
string sql = getPageListSql(primaryKey, queryFields, tableName, condition, orderBy, pageSize, pageIndex);
return Query(sql);
}
public static string GetPagingListSQL(string primaryKey, string queryFields, string tableName, string condition, string orderBy, int pageSize, int pageIndex)
{
string sql = getPageListSql(primaryKey, queryFields, tableName, condition, orderBy, pageSize, pageIndex);
return sql;
}
public static int GetRecordCount(string _ID, string _tbName, string _strCondition, int _Dist)
{
string sql = getPageListCounts( _ID, _tbName, _strCondition, _Dist);
object obj = DbHelperACE.GetSingle(sql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
#endregion
}
}