DbHelper重装上阵

lawbc 2010-07-22 09:04:54
看了以前写过的代码,拿来修改了下,下贴出来,大家看看有什么问题,或者哪里需要改进的,哈哈,互相促进

1、Configuration类


using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Reflection;

namespace LBC.Data
{
/// <summary>
/// LBC.Data配置类,负责读取配置,创建<see cref="LBC.Data.DbProviderFactory"/>
/// </summary>
public class Configuration
{
private static string GetDefaultConfigurationFilePath()
{
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath;
string binPath = relativeSearchPath == null ? baseDir : Path.Combine(baseDir, relativeSearchPath);
return Path.Combine(binPath, Environment.DefaultCfgFileName);
}

private DbProviderFactory BuildProviderFactory(IDictionary<string, string> settings)
{
return new DbProviderFactory(settings);
}

private IDictionary<string, string> GetSettings(XmlReader reader)
{
IDictionary<string, string> settings = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load(reader);
XmlNodeList list = document.SelectNodes("//" + Environment.SectionName + "/add");
foreach (XmlNode node in list)
{
settings[node.Attributes["key"].Value] = node.Attributes["value"].Value;
}
return settings;
}

public DbProviderFactory BuildProviderFactory()
{
IDictionary<string, string> settings = new Dictionary<string, string>();
Hashtable ht = ConfigurationManager.GetSection(Environment.SectionName) as Hashtable;
if (ht != null)
{
foreach (string key in ht.Keys)
{
settings[key] = ht[key].ToString();
}
return BuildProviderFactory(settings);
}
else
{
return BuildProviderFactory(GetDefaultConfigurationFilePath());
}
}

public DbProviderFactory BuildProviderFactory(string fileName)
{
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(fileName);
return BuildProviderFactory(reader);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}

public DbProviderFactory BuildProviderFactory(Assembly assembly, string resourceName)
{
Stream stream = null;
try
{
stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
throw new Exception("在程序集"+assembly.FullName+"中,不能创建"+resourceName+"资源");
}

return BuildProviderFactory(new XmlTextReader(stream));
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}

public DbProviderFactory BuildProviderFactory(XmlReader reader)
{
IDictionary<string, string> settings = GetSettings(reader);
return BuildProviderFactory(settings);
}

}
}

...全文
123 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
wwfgu00ing 2010-07-23
  • 打赏
  • 举报
回复
ff1222 2010-07-23
  • 打赏
  • 举报
回复

mark
lawbc 2010-07-23
  • 打赏
  • 举报
回复
5、3种常见数据库类型的实现

3个类名有错,后缀应该是Driver
happy664618843 2010-07-23
  • 打赏
  • 举报
回复
牛B 帮顶 学习
yby881109 2010-07-23
  • 打赏
  • 举报
回复
真的很好。。以后在项目里很有用。。
lawbc 2010-07-23
  • 打赏
  • 举报
回复

8、DriverProxy类

/// <summary>
/// IDriver代理类
/// </summary>
public class DriverProxy:IDriver
{
private IDriver driver;
private IDictionary<string, string> settings;

public DriverProxy(IDriver driver, IDictionary<string, string> settings)
{
this.driver = driver;
this.settings = settings;
}

#region IDriver 成员

public IDbCommand CreateCommand()
{
IDbCommand command = driver.CreateCommand();
if (command != null)
{
string timeout = string.Empty;
if (settings.TryGetValue(Environment.CommandTimeoutSectionName, out timeout))
{
if (!string.IsNullOrEmpty(timeout))
{
try
{
int commandTimeout = int.Parse(timeout);
if (commandTimeout > 0)
{
command.CommandTimeout = commandTimeout;
}
}
catch(InvalidCastException e)
{
throw new LBCDataException(Environment.CommandTimeoutSectionName + "设定值必须可以转换为int类型", e);
}
}
}
}
return command;
}

public IDbConnection CreateConnection()
{
IDbConnection connection = driver.CreateConnection();
if (connection != null)
{
string connectionString = string.Empty;
if (settings.TryGetValue(Environment.ConnectionStringSectionName, out connectionString))
{
if (!string.IsNullOrEmpty(connectionString))
{
connection.ConnectionString = connectionString;
}
else
{
throw new LBCDataException(Environment.ConnectionStringSectionName + "值不能为空");
}
}
}
return connection;
}

public IDbDataAdapter CreateDataAdapter()
{
return driver.CreateDataAdapter();
}

public IDataParameter CreateParameter()
{
return driver.CreateParameter();
}

#endregion
}
lawbc 2010-07-23
  • 打赏
  • 举报
回复
7、DbProviderFactory类

public class DbProviderFactory
{
private IDictionary<string, string> settings;

public DbProviderFactory(IDictionary<string, string> settings)
{
this.settings = settings;
}

public IDbProvider GetDbProvider()
{
string driverClass = string.Empty;
if (settings.TryGetValue(Environment.DriverClassSectionName, out driverClass))
{
try
{
IDriver driver = Activator.CreateInstance(Type.GetType(settings[Environment.DriverClassSectionName])) as IDriver;
DriverProxy driverProxy = new DriverProxy(driver, settings);
return new DbProvider(driverProxy);
}
catch(Exception e)
{
throw new LBCDataException("从" + Environment.DriverClassSectionName + "中创建IDriver类型失败。", e);
}
}
else
{
throw new LBCDataException("找不到"+Environment.DriverClassSectionName+"的设置。");
}
}
}
notfoundme 2010-07-23
  • 打赏
  • 举报
回复
兄弟,顶一个!学习...
lawbc 2010-07-22
  • 打赏
  • 举报
回复
6、IDbProvider实现类


/// <summary>
/// 数据库操作类,支持多数据库
/// </summary>
public class DbProvider : IDbProvider
{
private IDriver driver;

public DbProvider(IDriver driver)
{
this.driver = driver;
}

#region private utility methods & constructors

private void AttachParameters(IDbCommand command, IDataParameter[] parameters)
{
if (command == null)
{
throw new ArgumentNullException("command不能为空。");
}
if (parameters != null)
{
foreach (IDataParameter p in parameters)
{
if (p != null)
{
if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && (p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
}

private void PrepareCommand(IDbCommand command, IDbConnection connection, IDbTransaction transaction, CommandType commandType,
string commandText, IDataParameter[] parameters, out bool mustCloseConnection)
{
if (command == null) throw new ArgumentNullException("command不能为空。");
if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("commandText不能为空。");

if (connection.State != ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
}
command.Connection = connection;
command.CommandText = commandText;
if (transaction != null)
{
if (transaction.Connection == null) throw new ArgumentException("事务已提交或回滚。", "transaction");
command.Transaction = transaction;
}
command.CommandType = commandType;
if (parameters != null)
{
AttachParameters(command, parameters);
}
return;
}

#endregion private utility methods & constructors

public int ExecuteNonQuery(CommandType commandType, string commandText, params IDataParameter[] parameters)
{
using (IDbConnection connection = driver.CreateConnection())
{
IDbCommand cmd = driver.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (IDbTransaction)null, commandType, commandText, parameters, out mustCloseConnection);
int retval = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}

public DataSet ExecuteDataset(CommandType commandType, string commandText, params IDataParameter[] parameters)
{
using (IDbConnection connection = driver.CreateConnection())
{
IDbCommand cmd = driver.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (IDbTransaction)null, commandType, commandText, parameters, out mustCloseConnection);
IDbDataAdapter da = driver.CreateDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
cmd.Parameters.Clear();

if (mustCloseConnection)
connection.Close();
return ds;
}
}

public IDataReader ExecuteReader(CommandType commandType, string commandText, params IDataParameter[] parameters)
{
IDbConnection connection = null;
try
{
bool canClear = true;
bool mustCloseConnection = false;
connection = driver.CreateConnection();
IDbCommand cmd = driver.CreateCommand();
PrepareCommand(cmd, connection, null, commandType, commandText, parameters, out mustCloseConnection);
IDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
foreach (IDataParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
canClear = false;
}
if (canClear)
{
cmd.Parameters.Clear();
}
return dataReader;
}
catch
{
if (connection != null) connection.Close();
throw;
}

}

public object ExecuteScalar(CommandType commandType, string commandText, params IDataParameter[] parameters)
{
using (IDbConnection connection = driver.CreateConnection())
{
IDbCommand cmd = driver.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (IDbTransaction)null, commandType, commandText, parameters, out mustCloseConnection);
object retval = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}
}
lawbc 2010-07-22
  • 打赏
  • 举报
回复
5、3种常见数据库类型的实现

public class OdbcProvider : IDriver
{
#region IDriver 成员

public IDbCommand CreateCommand()
{
return new OdbcCommand();
}

public IDbConnection CreateConnection()
{
return new OdbcConnection();
}

public IDbDataAdapter CreateDataAdapter()
{
return new OdbcDataAdapter();
}

public IDataParameter CreateParameter()
{
return new OdbcParameter();
}

#endregion
}

public class OleDbProvider : IDriver
{
#region IDriver 成员

public IDbCommand CreateCommand()
{
return new OleDbCommand();
}

public IDbConnection CreateConnection()
{
return new OleDbConnection();
}

public IDbDataAdapter CreateDataAdapter()
{
return new OleDbDataAdapter();
}

public IDataParameter CreateParameter()
{
return new OleDbParameter();
}

#endregion
}

public class SqlClientProvider : IDriver
{
#region IDriver 成员

public IDbCommand CreateCommand()
{
return new SqlCommand();
}

public IDbConnection CreateConnection()
{
return new SqlConnection();
}

public IDbDataAdapter CreateDataAdapter()
{
return new SqlDataAdapter();
}

public IDataParameter CreateParameter()
{
return new SqlParameter();
}

#endregion
}
lawbc 2010-07-22
  • 打赏
  • 举报
回复

4、IDriver接口和IDbProvider接口

/// <summary>
/// 提供数据操作方法
/// </summary>
public interface IDbProvider
{
int ExecuteNonQuery(CommandType commandType, string commandText, params IDataParameter[] parameters);

DataSet ExecuteDataset(CommandType commandType, string commandText, params IDataParameter[] parameters);

IDataReader ExecuteReader(CommandType commandType, string commandText, params IDataParameter[] parameters);

object ExecuteScalar(CommandType commandType, string commandText, params IDataParameter[] parameters);
}

/// <summary>
/// 提供创建数据连接对象、命令对象、适配器对象、参数对象
/// </summary>
public interface IDriver
{
/// <summary>
/// 创建数据库命令对象
/// </summary>
/// <returns></returns>
IDbCommand CreateCommand();

/// <summary>
/// 创建数据库连接对象
/// </summary>
/// <returns></returns>
IDbConnection CreateConnection();

/// <summary>
/// 创建数据库适配器,用于填充DataSet对象
/// </summary>
/// <returns></returns>
IDbDataAdapter CreateDataAdapter();

/// <summary>
/// 创建数据库参数
/// </summary>
/// <returns></returns>
IDataParameter CreateParameter();
}
dengNeeo 2010-07-22
  • 打赏
  • 举报
回复
mark
我一般不这么写
没到这么的高度
lawbc 2010-07-22
  • 打赏
  • 举报
回复
3、LBCException 类


/// <summary>
/// LBC.Data异常类
/// </summary>
public class LBCException : Exception
{
public LBCException() : base("LBCException异常") { }
public LBCException(string message) : base(message) { }
protected LBCException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public LBCException(string message, Exception innerException) : base(message, innerException) { }

}
lawbc 2010-07-22
  • 打赏
  • 举报
回复
2、Environment类


/// <summary>
/// LBC.Data全局类,保存一些全局参数变量
/// </summary>
public sealed class Environment
{
public const string DefaultCfgFileName = "LBC.Data.xml";
public const string SectionName = "lbc-configuration/dataSource";
public const string DriverClassSectionName = "driverClass";
public const string ConnectionStringSectionName = "connectionString";
public const string CommandTimeoutSectionName = "commandTimeout";
}

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧