C#打造自己通用的数据库访问类解析

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#打造自己通用的数据库访问类

using System;

using System.Collections.Generic;

using System.Data;

using mon;

namespace NetSkycn.Data

{

///

/// 通用数据库访问类,封装了对数据库的常见操作

/// 作者:周公

/// 创建日期:2011-07-18

/// 修改日期:2012-04-12

/// 新浪微博地址:/zhoufoxcn

///

public sealed class DbUtility

{

public string ConnectionString { get; set; }

private DbProviderFactory providerFactory;

///

/// 构造函数

///

/// 数据库连接字符串

/// 数据库类型枚举,参见

public DbUtility(string connectionString, DbProviderType providerType)

{

ConnectionString = connectionString;

providerFactory = ProviderFactory.GetDbProviderFactory(providerType);

if (providerFactory == null)

{

throw new ArgumentException("Can't load DbProviderFactory for given value of providerType");

}

}

///

/// 对数据库执行增删改操作,返回受影响的行数。

///

/// 要执行的增删改的SQL语句

/// 执行增删改语句所需要的参数

///

public int ExecuteNonQuery(string sql, IList parameters)

{

return ExecuteNonQuery(sql, parameters, CommandType.Text);

}

///

/// 对数据库执行增删改操作,返回受影响的行数。

///

/// 要执行的增删改的SQL语句

/// 执行增删改语句所需要的参数

/// 执行的SQL语句的类型

///

public int ExecuteNonQuery(string sql, IList parameters, CommandType commandType)

{

using (DbCommand command = CreateDbCommand(sql, parameters, commandType))

{

command.Connection.Open();

int affectedRows = command.ExecuteNonQuery();

command.Connection.Close();

return affectedRows;

}

}

///

/// 执行一个查询语句,返回一个关联的DataReader实例

///

/// 要执行的查询语句

/// 执行SQL查询语句所需要的参数

///

public DbDataReader ExecuteReader(string sql, IList parameters)

{

return ExecuteReader(sql, parameters, CommandType.Text);

}

///

/// 执行一个查询语句,返回一个关联的DataReader实例

///

/// 要执行的查询语句

/// 执行SQL查询语句所需要的参数

/// 执行的SQL语句的类型

///

public DbDataReader ExecuteReader(string sql, IList parameters, CommandType commandType)

{

DbCommand command = CreateDbCommand(sql, parameters, commandType);

相关文档
最新文档