通用的数据库操作类(支持多种数据库)
我们在软件开发过程中,数据库是一个永久不变的话题,但是根据软件架构与客户要求的不同我们会选择不同的数据库,在C#中不同数据库操作编写代码不尽相同,下面提供一种通用的数据库操作方案,只需要根据config的配置就可以动态的选择不同的数据库.
通用的数据库操作类(支持多种数据库)
我们在软件开发过程中,数据库是一个永久不变的话题,但是根据软件架构与客户要求的不同我们会选择不同的数据库,在C#中不同数据库操作编写代码不尽相同,下面提供一种通用的数据库操作方案,只需要根据config的配置就可以动态的选择不同的数据库.
在配置文件中providerName指定不同的数据库类型.
<connectionStrings>
<add name="ConnectionString" connectionString=" ..." providerName="System.Data.OleDb" />
<add name="ConnectionString" connectionString=" ..." providerName="System.Data.SqlClient" />
</connectionStrings>
代码如下:
Code
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;
using System.Data.Common;
namespace DataBase
{
/// <summary>
/// 数据访问基础类
/// </summary>
class DataHelper
{
protected static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DbProviderFactory provider;
public DataHelper()
{
provider = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName);
}
#region 执行简单SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql(string SQLString)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (DbException E)
{
connection.Close();
connection.Dispose();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public void ExecuteSqlTran(ArrayList SQLStringList)
{
using (DbConnection conn = provider.CreateConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = conn;
using (DbTransaction 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 (DbException ex)
{
tx.Rollback();
conn.Close();
conn.Dispose();
throw ex;
}
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public object GetSingle(string SQLString)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public DbDataReader ExecuteReader(string strSQL)
{
DbConnection connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = strSQL;
try
{
connection.Open();
DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.Common.DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet GetDataSet(string SQLString)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
DataSet ds = new DataSet();
DbDataAdapter adapter = provider.CreateDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds, "ds");
return ds;
}
catch (DbException ex)
{
connection.Close();
connection.Dispose();
throw new Exception(ex.Message);
}
}
}
}
#endregion
#region 执行带参数的SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql(string SQLString, DbParameter[] cmdParms)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (DbException E)
{
connection.Close();
connection.Dispose();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public void ExecuteSqlTran(Hashtable SQLStringList)
{
using (DbConnection conn = provider.CreateConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
using (DbTransaction trans = conn.BeginTransaction())
{
using (DbCommand cmd = provider.CreateCommand())
{
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
DbParameter[] cmdParms = (DbParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch (DbException ex)
{
trans.Rollback();
conn.Close();
conn.Dispose();
throw ex;
}
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object),返回首行首列的值;
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public object GetSingle(string SQLString, DbParameter[] cmdParms)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
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 (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public DbDataReader ExecuteReader(string SQLString, DbParameter[] cmdParms)
{
DbConnection connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet GetDataSet(string SQLString, DbParameter[] cmdParms)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
using (DbDataAdapter da = provider.CreateDataAdapter())
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
return ds;
}
catch (DbException ex)
{
connection.Close();
connection.Dispose();
throw new Exception(ex.Message);
}
}
}
}
}
private void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] 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 (DbParameter parm in cmdParms)
{
cmd.Parameters.Add(parm);
}
}
}
#endregion
#region 存储过程操作
/// <summary>
/// 执行存储过程;
/// </summary>
/// <param name="storeProcName">存储过程名</param>
/// <param name="parameters">所需要的参数</param>
/// <returns>返回受影响的行数</returns>
public int RunProcedureExecuteSql(string storeProcName, DbParameter[] parameters)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
DbCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
return rows;
}
}
/// <summary>
/// 执行存储过程,返回首行首列的值
/// </summary>
/// <param name="storeProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>返回首行首列的值</returns>
public Object RunProcedureGetSingle(string storeProcName, DbParameter[] parameters)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
try
{
DbCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public DbDataReader RunProcedureGetDataReader(string storedProcName, DbParameter[] parameters)
{
DbConnection connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
DbDataReader returnReader;
DbCommand cmd = BuildQueryCommand(connection, storedProcName, parameters);
cmd.CommandType = CommandType.StoredProcedure;
returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return returnReader;
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>DataSet</returns>
public DataSet RunProcedureGetDataSet(string storedProcName, DbParameter[] parameters)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
DataSet dataSet = new DataSet();
DbDataAdapter sqlDA = provider.CreateDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet);
sqlDA.SelectCommand.Parameters.Clear();
sqlDA.Dispose();
return dataSet;
}
}
/// <summary>
/// 执行多个存储过程,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param>
public bool RunProcedureTran(Hashtable SQLStringList)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
using (DbTransaction trans = connection.BeginTransaction())
{
using (DbCommand cmd = provider.CreateCommand())
{
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
cmd.Connection = connection;
string storeName = myDE.Value.ToString();
DbParameter[] cmdParms = (DbParameter[])myDE.Key;
cmd.Transaction = trans;
cmd.CommandText = storeName;
cmd.CommandType = CommandType.StoredProcedure;
if (cmdParms != null)
{
foreach (DbParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
connection.Close();
connection.Dispose();
return false;
}
}
}
}
}
/// <summary>
/// 执行多个存储过程,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param>
public bool RunProcedureTran(C_HashTable SQLStringList)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
using (DbTransaction trans = connection.BeginTransaction())
{
using (DbCommand cmd = provider.CreateCommand())
{
try
{
//循环
foreach (DbParameter[] cmdParms in SQLStringList.Keys)
{
cmd.Connection = connection;
string storeName = SQLStringList[cmdParms].ToString();
cmd.Transaction = trans;
cmd.CommandText = storeName;
cmd.CommandType = CommandType.StoredProcedure;
if (cmdParms != null)
{
foreach (DbParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
connection.Close();
connection.Dispose();
return false;
}
}
}
}
}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private DbCommand BuildQueryCommand(DbConnection connection, string storedProcName, DbParameter[] parameters)
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
DbCommand command = provider.CreateCommand();
command.CommandText = storedProcName;
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (DbParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
return command;
}
#endregion
}
}
ing System;using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;
using System.Data.Common;
namespace DataBase
{
/// <summary>
/// 数据访问基础类
/// </summary>
class DataHelper
{
protected static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DbProviderFactory provider;
public DataHelper()
{
provider = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName);
}
#region 执行简单SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql(string SQLString)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (DbException E)
{
connection.Close();
connection.Dispose();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public void ExecuteSqlTran(ArrayList SQLStringList)
{
using (DbConnection conn = provider.CreateConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = conn;
using (DbTransaction 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 (DbException ex)
{
tx.Rollback();
conn.Close();
conn.Dispose();
throw ex;
}
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public object GetSingle(string SQLString)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public DbDataReader ExecuteReader(string strSQL)
{
DbConnection connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = strSQL;
try
{
connection.Open();
DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.Common.DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet GetDataSet(string SQLString)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
DataSet ds = new DataSet();
DbDataAdapter adapter = provider.CreateDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds, "ds");
return ds;
}
catch (DbException ex)
{
connection.Close();
connection.Dispose();
throw new Exception(ex.Message);
}
}
}
}
#endregion
#region 执行带参数的SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql(string SQLString, DbParameter[] cmdParms)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
cmd.Connection = connection;
cmd.CommandText = SQLString;
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (DbException E)
{
connection.Close();
connection.Dispose();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public void ExecuteSqlTran(Hashtable SQLStringList)
{
using (DbConnection conn = provider.CreateConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
using (DbTransaction trans = conn.BeginTransaction())
{
using (DbCommand cmd = provider.CreateCommand())
{
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
DbParameter[] cmdParms = (DbParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch (DbException ex)
{
trans.Rollback();
conn.Close();
conn.Dispose();
throw ex;
}
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object),返回首行首列的值;
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public object GetSingle(string SQLString, DbParameter[] cmdParms)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
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 (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回SqlDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public DbDataReader ExecuteReader(string SQLString, DbParameter[] cmdParms)
{
DbConnection connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet GetDataSet(string SQLString, DbParameter[] cmdParms)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand cmd = provider.CreateCommand())
{
using (DbDataAdapter da = provider.CreateDataAdapter())
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
return ds;
}
catch (DbException ex)
{
connection.Close();
connection.Dispose();
throw new Exception(ex.Message);
}
}
}
}
}
private void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] 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 (DbParameter parm in cmdParms)
{
cmd.Parameters.Add(parm);
}
}
}
#endregion
#region 存储过程操作
/// <summary>
/// 执行存储过程;
/// </summary>
/// <param name="storeProcName">存储过程名</param>
/// <param name="parameters">所需要的参数</param>
/// <returns>返回受影响的行数</returns>
public int RunProcedureExecuteSql(string storeProcName, DbParameter[] parameters)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
DbCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
return rows;
}
}
/// <summary>
/// 执行存储过程,返回首行首列的值
/// </summary>
/// <param name="storeProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>返回首行首列的值</returns>
public Object RunProcedureGetSingle(string storeProcName, DbParameter[] parameters)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
try
{
DbCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (DbException e)
{
connection.Close();
connection.Dispose();
throw new Exception(e.Message);
}
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public DbDataReader RunProcedureGetDataReader(string storedProcName, DbParameter[] parameters)
{
DbConnection connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
DbDataReader returnReader;
DbCommand cmd = BuildQueryCommand(connection, storedProcName, parameters);
cmd.CommandType = CommandType.StoredProcedure;
returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return returnReader;
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>DataSet</returns>
public DataSet RunProcedureGetDataSet(string storedProcName, DbParameter[] parameters)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
DataSet dataSet = new DataSet();
DbDataAdapter sqlDA = provider.CreateDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet);
sqlDA.SelectCommand.Parameters.Clear();
sqlDA.Dispose();
return dataSet;
}
}
/// <summary>
/// 执行多个存储过程,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param>
public bool RunProcedureTran(Hashtable SQLStringList)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
using (DbTransaction trans = connection.BeginTransaction())
{
using (DbCommand cmd = provider.CreateCommand())
{
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
cmd.Connection = connection;
string storeName = myDE.Value.ToString();
DbParameter[] cmdParms = (DbParameter[])myDE.Key;
cmd.Transaction = trans;
cmd.CommandText = storeName;
cmd.CommandType = CommandType.StoredProcedure;
if (cmdParms != null)
{
foreach (DbParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
connection.Close();
connection.Dispose();
return false;
}
}
}
}
}
/// <summary>
/// 执行多个存储过程,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param>
public bool RunProcedureTran(C_HashTable SQLStringList)
{
using (DbConnection connection = provider.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
using (DbTransaction trans = connection.BeginTransaction())
{
using (DbCommand cmd = provider.CreateCommand())
{
try
{
//循环
foreach (DbParameter[] cmdParms in SQLStringList.Keys)
{
cmd.Connection = connection;
string storeName = SQLStringList[cmdParms].ToString();
cmd.Transaction = trans;
cmd.CommandText = storeName;
cmd.CommandType = CommandType.StoredProcedure;
if (cmdParms != null)
{
foreach (DbParameter parameter in cmdParms)
{
cmd.Parameters.Add(parameter);
}
}
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
connection.Close();
connection.Dispose();
return false;
}
}
}
}
}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private DbCommand BuildQueryCommand(DbConnection connection, string storedProcName, DbParameter[] parameters)
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
DbCommand command = provider.CreateCommand();
command.CommandText = storedProcName;
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (DbParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
return command;
}
#endregion
}
}
2using System.Collections;
3using System.Collections.Specialized;
4using System.Data;
5using System.Configuration;
6using System.Data.Common;
7
8namespace DataBase
9{
10 /**//// <summary>
11 /// 数据访问基础类(基于SQLServer)
12 /// </summary>
13 class DataHelper
14 {
15 protected static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
16 DbProviderFactory provider;
17 public DataHelper()
18 {
19 provider = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName);
20 }
21
22 执行简单SQL语句#region 执行简单SQL语句
23
24 /**//// <summary>
25 /// 执行SQL语句,返回影响的记录数
26 /// </summary>
27 /// <param name="SQLString">SQL语句</param>
28 /// <returns>影响的记录数</returns>
29 public int ExecuteSql(string SQLString)
30 {
31 using (DbConnection connection = provider.CreateConnection())
32 {
33 connection.ConnectionString = connectionString;
34 using (DbCommand cmd = provider.CreateCommand())
35 {
36 cmd.Connection = connection;
37 cmd.CommandText = SQLString;
38 try
39 {
40 connection.Open();
41 int rows = cmd.ExecuteNonQuery();
42 return rows;
43 }
44 catch (DbException E)
45 {
46 connection.Close();
47 connection.Dispose();
48 throw new Exception(E.Message);
49 }
50 }
51 }
52 }
53
54 /**//// <summary>
55 /// 执行多条SQL语句,实现数据库事务。
56 /// </summary>
57 /// <param name="SQLStringList">多条SQL语句</param>
58 public void ExecuteSqlTran(ArrayList SQLStringList)
59 {
60 using (DbConnection conn = provider.CreateConnection())
61 {
62 conn.ConnectionString = connectionString;
63 conn.Open();
64 using (DbCommand cmd = provider.CreateCommand())
65 {
66 cmd.Connection = conn;
67 using (DbTransaction tx = conn.BeginTransaction())
68 {
69 cmd.Transaction = tx;
70 try
71 {
72 for (int n = 0; n < SQLStringList.Count; n++)
73 {
74 string strsql = SQLStringList[n].ToString();
75 if (strsql.Trim().Length > 1)
76 {
77 cmd.CommandText = strsql;
78 cmd.ExecuteNonQuery();
79 }
80 }
81 tx.Commit();
82 }
83 catch (DbException ex)
84 {
85 tx.Rollback();
86 conn.Close();
87 conn.Dispose();
88 throw ex;
89 }
90 }
91 }
92 }
93 }
94 /**//// <summary>
95 /// 执行一条计算查询结果语句,返回查询结果(object)。
96 /// </summary>
97 /// <param name="SQLString">计算查询结果语句</param>
98 /// <returns>查询结果(object)</returns>
99 public object GetSingle(string SQLString)
100 {
101 using (DbConnection connection = provider.CreateConnection())
102 {
103 connection.ConnectionString = connectionString;
104 using (DbCommand cmd = provider.CreateCommand())
105 {
106 cmd.Connection = connection;
107 cmd.CommandText = SQLString;
108 try
109 {
110 connection.Open();
111 object obj = cmd.ExecuteScalar();
112 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
113 {
114 return null;
115 }
116 else
117 {
118 return obj;
119 }
120 }
121 catch (DbException e)
122 {
123 connection.Close();
124 connection.Dispose();
125 throw new Exception(e.Message);
126 }
127 }
128 }
129 }
130 /**//// <summary>
131 /// 执行查询语句,返回SqlDataReader
132 /// </summary>
133 /// <param name="strSQL">查询语句</param>
134 /// <returns>SqlDataReader</returns>
135 public DbDataReader ExecuteReader(string strSQL)
136 {
137 DbConnection connection = provider.CreateConnection();
138 connection.ConnectionString = strSQL;
139 DbCommand cmd = provider.CreateCommand();
140 cmd.Connection = connection;
141 cmd.CommandText = strSQL;
142 try
143 {
144 connection.Open();
145 DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
146 return myReader;
147 }
148 catch (System.Data.Common.DbException e)
149 {
150 connection.Close();
151 connection.Dispose();
152 throw new Exception(e.Message);
153 }
154
155 }
156 /**//// <summary>
157 /// 执行查询语句,返回DataSet
158 /// </summary>
159 /// <param name="SQLString">查询语句</param>
160 /// <returns>DataSet</returns>
161 public DataSet GetDataSet(string SQLString)
162 {
163 using (DbConnection connection = provider.CreateConnection())
164 {
165 connection.ConnectionString = connectionString;
166 using (DbCommand cmd = provider.CreateCommand())
167 {
168 cmd.Connection = connection;
169 cmd.CommandText = SQLString;
170 try
171 {
172 DataSet ds = new DataSet();
173 DbDataAdapter adapter = provider.CreateDataAdapter();
174 adapter.SelectCommand = cmd;
175 adapter.Fill(ds, "ds");
176 return ds;
177 }
178 catch (DbException ex)
179 {
180 connection.Close();
181 connection.Dispose();
182 throw new Exception(ex.Message);
183 }
184 }
185 }
186 }
187 #endregion
188
189 执行带参数的SQL语句#region 执行带参数的SQL语句
190
191 /**//// <summary>
192 /// 执行SQL语句,返回影响的记录数
193 /// </summary>
194 /// <param name="SQLString">SQL语句</param>
195 /// <returns>影响的记录数</returns>
196 public int ExecuteSql(string SQLString, DbParameter[] cmdParms)
197 {
198 using (DbConnection connection = provider.CreateConnection())
199 {
200 connection.ConnectionString = connectionString;
201 using (DbCommand cmd = provider.CreateCommand())
202 {
203 cmd.Connection = connection;
204 cmd.CommandText = SQLString;
205 try
206 {
207 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
208 int rows = cmd.ExecuteNonQuery();
209 cmd.Parameters.Clear();
210 return rows;
211 }
212 catch (DbException E)
213 {
214 connection.Close();
215 connection.Dispose();
216 throw new Exception(E.Message);
217 }
218 }
219 }
220 }
221
222 /**//// <summary>
223 /// 执行多条SQL语句,实现数据库事务。
224 /// </summary>
225 /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
226 public void ExecuteSqlTran(Hashtable SQLStringList)
227 {
228 using (DbConnection conn = provider.CreateConnection())
229 {
230 conn.ConnectionString = connectionString;
231 conn.Open();
232 using (DbTransaction trans = conn.BeginTransaction())
233 {
234 using (DbCommand cmd = provider.CreateCommand())
235 {
236 try
237 {
238 //循环
239 foreach (DictionaryEntry myDE in SQLStringList)
240 {
241 string cmdText = myDE.Key.ToString();
242 DbParameter[] cmdParms = (DbParameter[])myDE.Value;
243 PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
244 int val = cmd.ExecuteNonQuery();
245 cmd.Parameters.Clear();
246 }
247 trans.Commit();
248 }
249 catch (DbException ex)
250 {
251 trans.Rollback();
252 conn.Close();
253 conn.Dispose();
254 throw ex;
255 }
256 }
257 }
258 }
259 }
260
261 /**//// <summary>
262 /// 执行一条计算查询结果语句,返回查询结果(object),返回首行首列的值;
263 /// </summary>
264 /// <param name="SQLString">计算查询结果语句</param>
265 /// <returns>查询结果(object)</returns>
266 public object GetSingle(string SQLString, DbParameter[] cmdParms)
267 {
268 using (DbConnection connection = provider.CreateConnection())
269 {
270 connection.ConnectionString = connectionString;
271 using (DbCommand cmd = provider.CreateCommand())
272 {
273 try
274 {
275 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
276 object obj = cmd.ExecuteScalar();
277 cmd.Parameters.Clear();
278 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
279 {
280 return null;
281 }
282 else
283 {
284 return obj;
285 }
286 }
287 catch (DbException e)
288 {
289 connection.Close();
290 connection.Dispose();
291 throw new Exception(e.Message);
292 }
293 }
294 }
295 }
296
297 /**//// <summary>
298 /// 执行查询语句,返回SqlDataReader
299 /// </summary>
300 /// <param name="strSQL">查询语句</param>
301 /// <returns>SqlDataReader</returns>
302 public DbDataReader ExecuteReader(string SQLString, DbParameter[] cmdParms)
303 {
304 DbConnection connection = provider.CreateConnection();
305 connection.ConnectionString = connectionString;
306 DbCommand cmd = provider.CreateCommand();
307 try
308 {
309 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
310 DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
311 cmd.Parameters.Clear();
312 return myReader;
313 }
314 catch (DbException e)
315 {
316 connection.Close();
317 connection.Dispose();
318 throw new Exception(e.Message);
319 }
320
321 }
322
323 /**//// <summary>
324 /// 执行查询语句,返回DataSet
325 /// </summary>
326 /// <param name="SQLString">查询语句</param>
327 /// <returns>DataSet</returns>
328 public DataSet GetDataSet(string SQLString, DbParameter[] cmdParms)
329 {
330 using (DbConnection connection = provider.CreateConnection())
331 {
332 using (DbCommand cmd = provider.CreateCommand())
333 {
334 using (DbDataAdapter da = provider.CreateDataAdapter())
335 {
336 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
337 da.SelectCommand = cmd;
338 DataSet ds = new DataSet();
339 try
340 {
341 da.Fill(ds, "ds");
342 cmd.Parameters.Clear();
343 return ds;
344 }
345 catch (DbException ex)
346 {
347 connection.Close();
348 connection.Dispose();
349 throw new Exception(ex.Message);
350 }
351 }
352 }
353 }
354 }
355
356 private void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
357 {
358 if (conn.State != ConnectionState.Open)
359 {
360 conn.Open();
361 }
362 cmd.Connection = conn;
363 cmd.CommandText = cmdText;
364 if (trans != null)
365 {
366 cmd.Transaction = trans;
367 }
368 cmd.CommandType = CommandType.Text;//cmdType;
369 if (cmdParms != null)
370 {
371 foreach (DbParameter parm in cmdParms)
372 {
373 cmd.Parameters.Add(parm);
374 }
375 }
376 }
377
378 #endregion
379
380 存储过程操作#region 存储过程操作
381 /**//// <summary>
382 /// 执行存储过程;
383 /// </summary>
384 /// <param name="storeProcName">存储过程名</param>
385 /// <param name="parameters">所需要的参数</param>
386 /// <returns>返回受影响的行数</returns>
387 public int RunProcedureExecuteSql(string storeProcName, DbParameter[] parameters)
388 {
389 using (DbConnection connection = provider.CreateConnection())
390 {
391 connection.ConnectionString = connectionString;
392 DbCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
393 int rows = cmd.ExecuteNonQuery();
394 cmd.Parameters.Clear();
395 connection.Close();
396 return rows;
397 }
398 }
399
400 /**//// <summary>
401 /// 执行存储过程,返回首行首列的值
402 /// </summary>
403 /// <param name="storeProcName">存储过程名</param>
404 /// <param name="parameters">存储过程参数</param>
405 /// <returns>返回首行首列的值</returns>
406 public Object RunProcedureGetSingle(string storeProcName, DbParameter[] parameters)
407 {
408 using (DbConnection connection = provider.CreateConnection())
409 {
410 connection.ConnectionString = connectionString;
411 try
412 {
413 DbCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
414 object obj = cmd.ExecuteScalar();
415 cmd.Parameters.Clear();
416 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
417 {
418 return null;
419 }
420 else
421 {
422 return obj;
423 }
424 }
425 catch (DbException e)
426 {
427 connection.Close();
428 connection.Dispose();
429 throw new Exception(e.Message);
430 }
431 }
432 }
433
434 /**//// <summary>
435 /// 执行存储过程
436 /// </summary>
437 /// <param name="storedProcName">存储过程名</param>
438 /// <param name="parameters">存储过程参数</param>
439 /// <returns>SqlDataReader</returns>
440 public DbDataReader RunProcedureGetDataReader(string storedProcName, DbParameter[] parameters)
441 {
442 DbConnection connection = provider.CreateConnection();
443 connection.ConnectionString = connectionString;
444 DbDataReader returnReader;
445 DbCommand cmd = BuildQueryCommand(connection, storedProcName, parameters);
446 cmd.CommandType = CommandType.StoredProcedure;
447 returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
448 cmd.Parameters.Clear();
449 return returnReader;
450 }
451
452 /**//// <summary>
453 /// 执行存储过程
454 /// </summary>
455 /// <param name="storedProcName">存储过程名</param>
456 /// <param name="parameters">存储过程参数</param>
457 /// <returns>DataSet</returns>
458 public DataSet RunProcedureGetDataSet(string storedProcName, DbParameter[] parameters)
459 {
460 using (DbConnection connection = provider.CreateConnection())
461 {
462 connection.ConnectionString = connectionString;
463 DataSet dataSet = new DataSet();
464 DbDataAdapter sqlDA = provider.CreateDataAdapter();
465 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
466 sqlDA.Fill(dataSet);
467 sqlDA.SelectCommand.Parameters.Clear();
468 sqlDA.Dispose();
469 return dataSet;
470 }
471 }
472
473 /**//// <summary>
474 /// 执行多个存储过程,实现数据库事务。
475 /// </summary>
476 /// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param>
477 public bool RunProcedureTran(Hashtable SQLStringList)
478 {
479 using (DbConnection connection = provider.CreateConnection())
480 {
481 connection.ConnectionString = connectionString;
482 connection.Open();
483 using (DbTransaction trans = connection.BeginTransaction())
484 {
485 using (DbCommand cmd = provider.CreateCommand())
486 {
487 try
488 {
489 //循环
490 foreach (DictionaryEntry myDE in SQLStringList)
491 {
492 cmd.Connection = connection;
493 string storeName = myDE.Value.ToString();
494 DbParameter[] cmdParms = (DbParameter[])myDE.Key;
495
496 cmd.Transaction = trans;
497 cmd.CommandText = storeName;
498 cmd.CommandType = CommandType.StoredProcedure;
499 if (cmdParms != null)
500 {
501 foreach (DbParameter parameter in cmdParms)
502 {
503 cmd.Parameters.Add(parameter);
504 }
505 }
506 int val = cmd.ExecuteNonQuery();
507 cmd.Parameters.Clear();
508 }
509 trans.Commit();
510 return true;
511 }
512 catch
513 {
514 trans.Rollback();
515 connection.Close();
516 connection.Dispose();
517 return false;
518 }
519 }
520 }
521 }
522 }
523
524 /**//// <summary>
525 /// 执行多个存储过程,实现数据库事务。
526 /// </summary>
527 /// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param>
528 public bool RunProcedureTran(C_HashTable SQLStringList)
529 {
530 using (DbConnection connection = provider.CreateConnection())
531 {
532 connection.ConnectionString = connectionString;
533 connection.Open();
534 using (DbTransaction trans = connection.BeginTransaction())
535 {
536 using (DbCommand cmd = provider.CreateCommand())
537 {
538 try
539 {
540 //循环
541 foreach (DbParameter[] cmdParms in SQLStringList.Keys)
542 {
543 cmd.Connection = connection;
544 string storeName = SQLStringList[cmdParms].ToString();
545
546 cmd.Transaction = trans;
547 cmd.CommandText = storeName;
548 cmd.CommandType = CommandType.StoredProcedure;
549 if (cmdParms != null)
550 {
551 foreach (DbParameter parameter in cmdParms)
552 {
553 cmd.Parameters.Add(parameter);
554 }
555 }
556 int val = cmd.ExecuteNonQuery();
557 cmd.Parameters.Clear();
558 }
559 trans.Commit();
560 return true;
561 }
562 catch
563 {
564 trans.Rollback();
565 connection.Close();
566 connection.Dispose();
567 return false;
568 }
569 }
570 }
571 }
572 }
573
574 /**//// <summary>
575 /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
576 /// </summary>
577 /// <param name="connection">数据库连接</param>
578 /// <param name="storedProcName">存储过程名</param>
579 /// <param name="parameters">存储过程参数</param>
580 /// <returns>SqlCommand</returns>
581 private DbCommand BuildQueryCommand(DbConnection connection, string storedProcName, DbParameter[] parameters)
582 {
583 if (connection.State != ConnectionState.Open)
584 {
585 connection.Open();
586 }
587 DbCommand command = provider.CreateCommand();
588 command.CommandText = storedProcName;
589 command.Connection = connection;
590 command.CommandType = CommandType.StoredProcedure;
591 if (parameters != null)
592 {
593 foreach (DbParameter parameter in parameters)
594 {
595 command.Parameters.Add(parameter);
596 }
597 }
598 return command;
599 }
600 #endregion
601 }
602}
603
(作者:侯垒)