Access数据库访问助手类
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.OleDb; using System.Collections; namespace TaoBaoSyncLibrary.Dal { /// <summary> /// Access數(shù)據(jù)庫訪問助手類 /// </summary> public class DBHelper_Access { //數(shù)據(jù)庫連接字符串(web.config來配置) public static string dataBasePath = @"C:/Users/zhangqs008/Documents/TaoBaoSyncDataBase.accdb"; // public static string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + dataBasePath + ";"; //2003版本 public static string connectionString = "provider=microsoft.ace.oledb.12.0;Data Source=" + dataBasePath + ";"; //2007版本 public DBHelper_Access() { } #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; object obj = DBHelper_Access.GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } /// <summary> /// 執(zhí)行SQL語句判斷是否存在 /// </summary> /// <param name="strSql">SQL語句</param> /// <returns>true存在,false 不存在</returns> public static bool Exists(string strSql) { object obj = DBHelper_Access.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; } } /// <summary> /// 執(zhí)行SQL語句判斷是否存在(含參數(shù)) /// </summary> /// <param name="strSql">SQL語句</param> /// <param name="cmdParms">參數(shù)</param> /// <returns>true存在,false 不存在</returns> public static bool Exists(string strSql, params OleDbParameter[] cmdParms) { object obj = DBHelper_Access.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 執(zhí)行簡(jiǎn)單SQL語句 /// <summary> /// 執(zhí)行SQL語句,返回影響的記錄數(shù) /// </summary> /// <param name="SQLString">SQL語句</param> /// <returns>影響的記錄數(shù)</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> /// 執(zhí)行SQL語句,設(shè)置命令的執(zhí)行等待時(shí)間 /// </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> /// 執(zhí)行多條SQL語句,實(shí)現(xiàn)數(shù)據(jù)庫事務(wù)。 /// </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> /// 向數(shù)據(jù)庫里插入圖像格式的字段(和上面情況類似的另一種實(shí)例) /// </summary> /// <param name="strSQL">SQL語句</param> /// <param name="fs">圖像字節(jié),數(shù)據(jù)庫的字段類型為image的情況</param> /// <returns>影響的記錄數(shù)</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> /// 執(zhí)行一條計(jì)算查詢結(jié)果語句,返回查詢結(jié)果(object)。 /// </summary> /// <param name="SQLString">計(jì)算查詢結(jié)果語句</param> /// <returns>查詢結(jié)果(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> /// 執(zhí)行查詢語句,返回SqlDataReader(使用該方法切記要手工關(guān)閉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 //不能在此關(guān)閉,否則,返回的對(duì)象將無法使用 //{ // cmd.Dispose(); // connection.Close(); //} } /// <summary> /// 執(zhí)行查詢語句,返回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> /// 執(zhí)行查詢語句,返回DataSet,設(shè)置命令的執(zhí)行等待時(shí)間 /// </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 執(zhí)行帶參數(shù)的SQL語句 /// <summary> /// 執(zhí)行SQL語句,返回影響的記錄數(shù) /// </summary> /// <param name="SQLString">SQL語句</param> /// <returns>影響的記錄數(shù)</returns> public static bool 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 > 0 ? true : false; } catch (System.Data.OleDb.OleDbException E) { throw new Exception(E.Message); } } } } /// <summary> /// 執(zhí)行多條SQL語句,實(shí)現(xiàn)數(shù)據(jù)庫事務(wù)。 /// </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 { //循環(huán) 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> /// 執(zhí)行一條計(jì)算查詢結(jié)果語句,返回查詢結(jié)果(object)。 /// </summary> /// <param name="SQLString">計(jì)算查詢結(jié)果語句</param> /// <returns>查詢結(jié)果(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> /// 執(zhí)行查詢語句,返回SqlDataReader (使用該方法切記要手工關(guān)閉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 //不能在此關(guān)閉,否則,返回的對(duì)象將無法使用 //{ // cmd.Dispose(); // connection.Close(); //} } /// <summary> /// 執(zhí)行查詢語句,返回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 獲取根據(jù)指定字段排序并分頁查詢。 /**/ /// <summary> /// 分頁查詢數(shù)據(jù)記錄總數(shù)獲取 /// </summary> /// <param name="_tbName">----要顯示的表或多個(gè)表的連接</param> /// <param name="_ID">----主表的主鍵</param> /// <param name="_strCondition">----查詢條件,不需where</param> /// <param name="_Dist">----是否添加查詢字段的 DISTINCT 默認(rèn)0不添加/1添加</param> /// <returns></returns> public static string getPageListCounts(string _ID, string _tbName, string _strCondition, int _Dist) { //---存放取得查詢結(jié)果總數(shù)的查詢語句 //---對(duì)含有DISTINCT的查詢進(jìn)行SQL構(gòu)造 //---對(duì)含有DISTINCT的總數(shù)查詢進(jìn)行SQL構(gòu)造 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">分頁數(shù)(不能為空)</param> /// <param name="pageIndex">當(dāng)前頁,起始為: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:分頁數(shù)量 //1:提取字段 //2:表 //3:條件 //4:主鍵不存在的記錄 //5:排序 SqlSelect = " select top {0} {1} from {2} {3} {4} {5}"; //0:主鍵 //1:TOP數(shù)量,為分頁數(shù)*(排序號(hào)-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> /// 獲取根據(jù)指定字段排序并分頁查詢。DataSet /// </summary> /// <param name="pageSize">每頁要顯示的記錄的數(shù)目</param> /// <param name="pageIndex">要顯示的頁的索引</param> /// <param name="tableName">要查詢的數(shù)據(jù)表</param> /// <param name="queryFields">要查詢的字段,如果是全部字段請(qǐng)?zhí)顚?#xff1a;*</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 = DBHelper_Access.GetSingle(sql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } #endregion /// <summary> /// 實(shí)例化SQL查詢參數(shù) /// </summary> /// <param name="parmName">參數(shù)名</param> /// <param name="parmType">參數(shù)類型</param> /// <param name="parmValue">參數(shù)值</param> /// <returns></returns> public static OleDbParameter GetParm(string parmName, OleDbType parmType, object parmValue) { OleDbParameter parm = new OleDbParameter(); parm.OleDbType = parmType; parm.ParameterName = parmName; parm.Value = parmValue; return parm; } /// <summary> /// 過濾掉字符串中會(huì)引起注入攻擊的字符 /// </summary> /// <param name="strchar">要過濾的字符串</param> /// <returns>已過濾的字符串</returns> public static string FilterBadChar(string strchar) { string newstrChar = string.Empty; if (string.IsNullOrEmpty(strchar)) { newstrChar = string.Empty; } else { newstrChar = strchar.Replace("'", string.Empty); } return newstrChar; } } } ?
轉(zhuǎn)載于:https://www.cnblogs.com/zhangqs008/archive/2011/06/12/2341130.html
總結(jié)
以上是生活随笔為你收集整理的Access数据库访问助手类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大气
- 下一篇: 肉肉谈对需求设计的想法--到底是功能驱动