C# AccessHelper:封装OleDb数据库操作工具类
本文介绍一个基于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
}
注意事项与改进建议
在使用上述工具类进行实际开发时,请注意以下几点:
- 安全性:示例代码中存在硬编码的连接字符串(包括密码)。在实际部署中,请务必将连接字符串移至
App.config或Web.config文件中,并使用更安全的凭据管理方式。 - 性能:代码中的
DataTable方法引入了简单的本地缓存机制(通过Common类)。如果在高并发场景下使用该方案,需要考虑内存占用与缓存过期策略。 - 资源释放:对于
ExecuteSql和非引用型的DataSet/DataTable方法,由于类内部自动处理了finally块的连接关闭,开发者通常无需关心连接的回收;但对于返回值是OleDbDataReader的方法,必须在业务逻辑中显式调用.Close()。 - 兼容性:该代码依赖
Microsoft.Jet.OLEDB.4.0驱动。如果使用 64位环境或较新的 Access 格式(.accdb),请改用 ACE OLEDB 提供程序(如Microsoft.ACE.OLEDB.12.0)并进行相应的注册表设置调整。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









