C# AccessHelper:封装OleDb数据库操作工具类

巷口听风
巷口听风
发布时间:2026-10-14 | 2人浏览过
原创

本文介绍一个基于C#的AccessHelper工具类,旨在通过静态方法封装System.Data.OleDb相关操作,简化对Access数据库的增删改查及结果集(DataSet、DataTable、DataView)获取流程。

核心功能与代码实现

该 AccessHelper 类主要处理以下任务:

  • 数据库连接管理:内部维护静态连接对象,提供打开与关闭状态的安全检查。
  • 通用SQL执行:用于执行不带返回值的SQL语句(如 INSERT、UPDATE、DELETE)。
  • 结果集获取:支持将查询结果填充至 OleDbDataReader、DataSet、DataTable 或 DataView。

以下是完整的核心实现代码:

using System;
using System.Data;
using System.Configuration;
using System.Data.OleDb;
using ahwildlife.Utils;

<!-- 此段代码演示了如何封装访问Access数据库的基础方法 -->
public class AccessHelper
{
    #region 变量定义
    protected static OleDbConnection conn = new OleDbConnection();
    protected static OleDbCommand comm = new OleDbCommand();
    // 建议在实际工程中,将硬编码的ConnectionString改为从配置文件读取
    protected static string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ahwildlife.mdb;Persist Security Info=False;Jet OLEDB:Database Password=sa;";
    #endregion
    
    #region 数据库连接控制
    /// <summary>
/// 如果连接未打开,则建立连接并配置命令对象 /// </summary>
private static void openConnection() { if (conn.State == ConnectionState.Closed) { conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ahwildlife.mdb;Persist Security Info=False;Jet OLEDB:Database Password=sa;"; comm.Connection = conn; try { conn.Open(); } catch (Exception ex) { throw new Exception(ex.Message); } } } /// <summary>
/// 安全地关闭连接并释放资源 /// </summary>
private static void closeConnection() { if (conn.State == ConnectionState.Open) { conn.Close(); conn.Dispose(); comm.Dispose(); } } #endregion #region 执行非查询SQL语句 /// <summary>
/// 直接执行SQL字符串,适用于Insert/Update/Delete等操作 /// </summary>
public static void ExecuteSql(string sqlstr) { try { openConnection(); comm.CommandType = CommandType.Text; comm.CommandText = sqlstr; comm.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { closeConnection(); } } #endregion #region 返回OleDbDataReader对象 /// <summary>
/// 返回指定sql语句的OleDbDataReader对象
/// 注意:调用者使用完毕后必须手动关闭DataReader和连接 /// </summary>
public static OleDbDataReader DataReader(string sqlstr) { OleDbDataReader dr = null; try { openConnection(); comm.CommandText = sqlstr; comm.CommandType = CommandType.Text; // CommandBehavior.CloseConnection 确保在关闭DataReader时同时关闭底层连接 dr = comm.ExecuteReader(CommandBehavior.CloseConnection); } catch { try { dr.Close(); closeConnection(); } catch { } } return dr; } /// <summary>
/// 以引用方式返回DataReader对象 /// </summary>
public static void DataReader(string sqlstr, ref OleDbDataReader dr) { try { openConnection(); comm.CommandText = sqlstr; comm.CommandType = CommandType.Text; dr = comm.ExecuteReader(CommandBehavior.CloseConnection); } catch { try { if (dr != null && !dr.IsClosed) dr.Close(); } catch { } finally { closeConnection(); } } } #endregion #region 返回DataSet对象 /// <summary>
/// 执行SQL并将结果填充到新的DataSet中 /// </summary>
public static DataSet DataSet(string sqlstr) { DataSet ds = new DataSet(); OleDbDataAdapter da = new OleDbDataAdapter(); try { openConnection(); comm.CommandType = CommandType.Text; comm.CommandText = sqlstr; da.SelectCommand = comm; da.Fill(ds); } catch (Exception e) { throw new Exception(e.Message); } finally { closeConnection(); } return ds; } /// <summary>
/// 将结果填充到传入的现有DataSet实例中 /// </summary>
public static void DataSet(string sqlstr, ref DataSet ds) { OleDbDataAdapter da = new OleDbDataAdapter(); try { openConnection(); comm.CommandType = CommandType.Text; comm.CommandText = sqlstr; da.SelectCommand = comm; da.Fill(ds); } catch (Exception e) { throw new Exception(e.Message); } finally { closeConnection(); } } #endregion #region 返回DataTable对象 /// <summary>
/// 执行SQL并将结果填充到新的DataTable中 /// </summary>
public static DataTable DataTable(string sqlstr) { DataTable dt = Common.GetDataTableCache(sqlstr); // 读缓存 if (dt != null) { return dt.Copy(); } else { dt = new DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(); try { using (OleDbConnection conn = new OleDbConnection()) { conn.ConnectionString = connectionString; conn.Open(); using (OleDbCommand comm = new OleDbCommand()) { comm.Connection = conn; comm.CommandType = CommandType.Text; comm.CommandText = sqlstr; da.SelectCommand = comm; da.Fill(dt); } } } catch (Exception e) { throw new Exception(e.Message); } finally { closeConnection(); } Common.InsertDataTableCache(sqlstr, dt); // 添加缓存 return dt.Copy(); } } /// <summary>
/// 将结果填充到传入的现有DataTable实例中 /// </summary>
public static void DataTable(string sqlstr, ref DataTable dt) { OleDbDataAdapter da = new OleDbDataAdapter(); try { openConnection(); comm.CommandType = CommandType.Text; comm.CommandText = sqlstr; da.SelectCommand = comm; da.Fill(dt); } catch (Exception e) { throw new Exception(e.Message); } finally { closeConnection(); } } #endregion #region 返回DataView对象 /// <summary>
/// 执行SQL并将其第一个表转换为DataView供前端绑定等使用 /// </summary>
public static DataView DataView(string sqlstr) { OleDbDataAdapter da = new OleDbDataAdapter(); DataView dv = new DataView(); DataSet ds = new DataSet(); try { openConnection(); comm.CommandType = CommandType.Text; comm.CommandText = sqlstr; da.SelectCommand = comm; da.Fill(ds); dv = ds.Tables[0].DefaultView; } catch (Exception e) { throw new Exception(e.Message); } finally { closeConnection(); } return dv; } #endregion }

注意事项与改进建议

在使用上述工具类进行实际开发时,请注意以下几点:

  1. 安全性:示例代码中存在硬编码的连接字符串(包括密码)。在实际部署中,请务必将连接字符串移至 App.config 或 Web.config 文件中,并使用更安全的凭据管理方式。
  2. 性能:代码中的 DataTable 方法引入了简单的本地缓存机制(通过 Common 类)。如果在高并发场景下使用该方案,需要考虑内存占用与缓存过期策略。
  3. 资源释放:对于 ExecuteSql 和非引用型的 DataSet/DataTable 方法,由于类内部自动处理了 finally 块的连接关闭,开发者通常无需关心连接的回收;但对于返回值是 OleDbDataReader 的方法,必须在业务逻辑中显式调用 .Close()。
  4. 兼容性:该代码依赖 Microsoft.Jet.OLEDB.4.0 驱动。如果使用 64位环境或较新的 Access 格式(.accdb),请改用 ACE OLEDB 提供程序(如 Microsoft.ACE.OLEDB.12.0)并进行相应的注册表设置调整。
以上就是C# AccessHelper封装OleDb数据库操作类的详细内容,更多关于Access数据库操作技巧的资料请关注本站其它相关文章!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表