程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#.NET萬能數據庫訪問封裝類(ACCESS、SQLServer、Oracle)

C#.NET萬能數據庫訪問封裝類(ACCESS、SQLServer、Oracle)

編輯:關於C#
 

在app.config文件中寫上數據庫中連接信息:

<appSettings>
<add key="connectionstring" value="Data Source=LocalHost;Initial Catalog=Test001;User ID=sa;Password=aaaaaa" />
<add key="DataType" value="SqlServer" />
</appSettings>

app.config文件中代碼解析:

<appSettings>
    <add key="connectionstring" value="Data Source=你的數據庫器(本機可用LocalHost,如果是EXPRESS開發版則必須是.\SQLEXPRESS);Initial Catalog=數據庫名字;User ID=用戶名;Password=你自己的密碼" />
    <add key="TemplatePATH" value="Template" />
</appSettings>

小注: 同理web程序,可以把數據庫連接信息放到web.config中。 C#.NET萬能數據庫訪問封裝類代碼如下:(該代碼來自百度文庫,非自己編寫)

using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.OracleClient;
using System.Configuration;
using System.Reflection;

namespace SystemFramework.DAL
{
class DataBaseLayer
{
#region 屬性變量
private string connectionString;
public string ConntionString
{
get
{
return connectionString;
}
set
{
connectionString = value;
}
}
//數據訪問基礎類--構造函數
public DataBaseLayer(string strConnect, string dataType)
{
this.ConntionString = strConnect;
this.DbType = dataType;
}
//數據訪問基礎類--構造函數
public DataBaseLayer()
{
this.connectionString =ConfigurationManager.AppSettings["ConnectionString"];
this.dbType =ConfigurationManager.AppSettings["DataType"];
//也可以在代碼中直接賦值
//this.connectionString = "data source=192.168.1.43;user id=sa;pwd=sa;database=temphrdb";
//this.dbType = "SqlServer";
}
/// <summary>
/// 數據庫類型
/// </summary>
private string dbType;
public string DbType
{
get
{
if (string.IsNullOrEmpty(dbType))
{
return "Access";
}
else
{
return dbType;
}
}
set
{
if (value != string.Empty && value != null)
{
dbType = value;
}
if (string.IsNullOrEmpty(dbType))
{
dbType =ConfigurationManager.AppSettings["DataType"];
}
if (string.IsNullOrEmpty(dbType))
{
dbType = "Access";
}
}
}
#endregion

#region 轉換參數
private System.Data.IDbDataParameter iDbPara(string ParaName, string DataType)
{
switch (this.DbType)
{
case "SqlServer":
return GetSqlPara(ParaName, DataType);
case "Oracle":
return GetOleDbPara(ParaName, DataType);
case "Access":
return GetOleDbPara(ParaName, DataType);
default:
return GetSqlPara(ParaName, DataType);
}
}

private SqlParameter GetSqlPara(string ParaName, string DataType)
{
switch (DataType)
{
case "Decimal":
return new SqlParameter(ParaName, SqlDbType.Decimal);
case "Varchar":
return new SqlParameter(ParaName, SqlDbType.VarChar);
case "DateTime":
return new SqlParameter(ParaName, SqlDbType.DateTime);
case "Iamge":
return new SqlParameter(ParaName, SqlDbType.Image);
case "Int":
return new SqlParameter(ParaName, SqlDbType.Int);
case "Text":
return new SqlParameter(ParaName, SqlDbType.NText);
default:
return new SqlParameter(ParaName, SqlDbType.VarChar);
}
}

private OracleParameter GetOraclePara(string ParaName, string DataType)
{
switch (DataType)
{
case "Decimal":
return new OracleParameter(ParaName, OracleType.Double);
case "Varchar":
return new OracleParameter(ParaName, OracleType.VarChar);
case "DateTime":
return new OracleParameter(ParaName, OracleType.DateTime);
case "Iamge":
return new OracleParameter(ParaName, OracleType.BFile);
case "Int":
return new OracleParameter(ParaName, OracleType.Int32);
case "Text":
return new OracleParameter(ParaName, OracleType.LongVarChar);
default:
return new OracleParameter(ParaName, OracleType.VarChar);

}
}

private OleDbParameter GetOleDbPara(string ParaName, string DataType)
{
switch (DataType)
{
case "Decimal":
return new OleDbParameter(ParaName, System.Data.DbType.Decimal);
case "Varchar":
return new OleDbParameter(ParaName, System.Data.DbType.String);
case "DateTime":
return new OleDbParameter(ParaName, System.Data.DbType.DateTime);
case "Iamge":
return new OleDbParameter(ParaName, System.Data.DbType.Binary);
case "Int":
return new OleDbParameter(ParaName, System.Data.DbType.Int32);
case "Text":
return new OleDbParameter(ParaName, System.Data.DbType.String);
default:
return new OleDbParameter(ParaName, System.Data.DbType.String);
}
}
#endregion

#region 創建 Connection 和 Command

private IDbConnection GetConnection()
{
switch (this.DbType)
{
case "SqlServer":
return new SqlConnection(this.ConntionString);
case "Oracle":
return new OracleConnection(this.ConntionString);
case "Access":
return new OleDbConnection(this.ConntionString);
default:
return new SqlConnection(this.ConntionString);
}
}


private IDbCommand GetCommand(string Sql, IDbConnection iConn)
{
switch (this.DbType)
{
case "SqlServer":
return new SqlCommand(Sql, (SqlConnection)iConn);
case "Oracle":
return new OracleCommand(Sql, (OracleConnection)iConn);
case "Access":
return new OleDbCommand(Sql, (OleDbConnection)iConn);
default:
return new SqlCommand(Sql, (SqlConnection)iConn);
}
}

private IDbCommand GetCommand()
{
switch (this.DbType)
{
case "SqlServer":
return new SqlCommand();
case "Oracle":
return new OracleCommand();
case "Access":
return new OleDbCommand();
default:
return new SqlCommand();
}
}

private IDataAdapter GetAdapater(string Sql, IDbConnection iConn)
{
switch (this.DbType)
{
case "SqlServer":
return new SqlDataAdapter(Sql, (SqlConnection)iConn);
case "Oracle":
return new OracleDataAdapter(Sql, (OracleConnection)iConn);
case "Access":
return new OleDbDataAdapter(Sql, (OleDbConnection)iConn);
default:
return new SqlDataAdapter(Sql, (SqlConnection)iConn); ;
}
}

private IDataAdapter GetAdapater()
{
switch (this.DbType)
{
case "SqlServer":
return new SqlDataAdapter();
case "Oracle":
return new OracleDataAdapter();
case "Access":
return new OleDbDataAdapter();
default:
return new SqlDataAdapter();
}
}

private IDataAdapter GetAdapater(IDbCommand iCmd)
{
switch (this.DbType)
{
case "SqlServer":
return new SqlDataAdapter((SqlCommand)iCmd);
case "Oracle":
return new OracleDataAdapter((OracleCommand)iCmd);
case "Access":
return new OleDbDataAdapter((OleDbCommand)iCmd);
default:
return new SqlDataAdapter((SqlCommand)iCmd);
}
}
#endregion

#region 執行簡單SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public int ExecuteSql(string SqlString)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(SqlString, iConn))
{
iConn.Open();
try
{
int rows = iCmd.ExecuteNonQuery();
return rows;
}
catch (System.Exception E)
{
throw new Exception(E.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public void ExecuteSqlTran(ArrayList SQLStringList)
{
//using作為語句,用於定義一個范圍,在此范圍的末尾將釋放對象
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
using (IDbCommand iCmd = GetCommand())
{
iCmd.Connection = iConn;
using (System.Data.IDbTransaction iDbTran = iConn.BeginTransaction())
{
iCmd.Transaction = iDbTran;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
iCmd.CommandText = strsql;
iCmd.ExecuteNonQuery();
}
}
iDbTran.Commit();
}
catch (System.Exception E)
{
iDbTran.Rollback();
throw new Exception(E.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}
}

/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <param name="content">參數內容,比如一個字段是格式復雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>影響的記錄數</returns>
public int ExecuteSql(string SqlString, string content)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(SqlString, iConn))
{
IDataParameter myParameter = this.iDbPara("@content", "Text");
myParameter.Value = content;
iCmd.Parameters.Add(myParameter);
iConn.Open();
try
{
int rows = iCmd.ExecuteNonQuery();
return rows;
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 向數據庫裡插入圖像格式的字段(和上面情況類似的另一種實例)
/// </summary>
/// <param name="strSQL">SQL語句</param>
/// <param name="fs">圖像字節,數據庫的字段類型為image的情況</param>
/// <returns>影響的記錄數</returns>
public int ExecuteSqlInsertImg(string SqlString, byte[] fs)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(SqlString, iConn))
{
IDataParameter myParameter = this.iDbPara("@content", "Image");
myParameter.Value = fs;
iCmd.Parameters.Add(myParameter);
iConn.Open();
try
{
int rows = iCmd.ExecuteNonQuery();
return rows;
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public object GetSingle(string SqlString)
{
using (IDbConnection iConn = GetConnection())
{
using (IDbCommand iCmd = GetCommand(SqlString, iConn))
{
iConn.Open();
try
{
object obj = iCmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行查詢語句,返回IDataAdapter
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>IDataAdapter</returns>
public IDataAdapter ExecuteReader(string strSQL)
{
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
try
{
IDataAdapter iAdapter = this.GetAdapater(strSQL, iConn);
return iAdapter;
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}

/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataSet</returns>
public DataSet Query(string sqlString)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(sqlString, iConn))
{
DataSet ds = new DataSet();
iConn.Open();
try
{
IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
iAdapter.Fill(ds);
return ds;
}
catch (System.Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="sqlString">查詢語句</param>
/// <param name="dataSet">要填充的DataSet</param>
/// <param name="tableName">要填充的表名</param>
/// <returns>DataSet</returns>
public DataSet Query(string sqlString, DataSet dataSet, string tableName)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(sqlString, iConn))
{
iConn.Open();
try
{
IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
((OleDbDataAdapter)iAdapter).Fill(dataSet, tableName);
return dataSet;
}
catch (System.Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行SQL語句 返回存儲過程
/// </summary>
/// <param name="sqlString">Sql語句</param>
/// <param name="dataSet">要填充的DataSet</param>
/// <param name="startIndex">開始記錄</param>
/// <param name="pageSize">頁面記錄大小</param>
/// <param name="tableName">表名稱</param>
/// <returns>DataSet</returns>
public DataSet Query(string sqlString, DataSet dataSet, int startIndex, int pageSize, string tableName)
{
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
try
{
IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);

((OleDbDataAdapter)iAdapter).Fill(dataSet, startIndex, pageSize, tableName);

return dataSet;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}

/// <summary>
/// 執行查詢語句,向XML文件寫入數據
/// </summary>
/// <param name="sqlString">查詢語句</param>
/// <param name="xmlPath">XML文件路徑</param>
public void WriteToXml(string sqlString, string xmlPath)
{
Query(sqlString).WriteXml(xmlPath);
}

/// <summary>
/// 執行查詢語句
/// </summary>
/// <param name="SqlString">查詢語句</param>
/// <returns>DataTable </returns>
public DataTable ExecuteQuery(string sqlString)
{
using (IDbConnection iConn = this.GetConnection())
{
//IDbCommand iCmd = GetCommand(sqlString,iConn);
DataSet ds = new DataSet();
try
{
IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
iAdapter.Fill(ds);
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
return ds.Tables[0];
}
}

/// <summary>
/// 執行查詢語句
/// </summary>
/// <param name="SqlString">查詢語句</param>
/// <returns>DataTable </returns>
public DataTable ExecuteQuery(string SqlString, string Proc)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(SqlString, iConn))
{
iCmd.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
try
{
IDataAdapter iDataAdapter = this.GetAdapater(SqlString, iConn);
iDataAdapter.Fill(ds);
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
return ds.Tables[0];
}
}
}

/// <summary>
/// 執行查詢,並以DataView返回結果集
/// </summary>
/// <param name="Sql">SQL語句</param>
/// <returns>DataView</returns>
public DataView ExeceuteDataView(string Sql)
{
using (IDbConnection iConn = this.GetConnection())
{
using (IDbCommand iCmd = GetCommand(Sql, iConn))
{
DataSet ds = new DataSet();
try
{
IDataAdapter iDataAdapter = this.GetAdapater(Sql, iConn);
iDataAdapter.Fill(ds);
return ds.Tables[0].DefaultView;
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

#endregion

#region 執行帶參數的SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public int ExecuteSql(string SQLString, params IDataParameter[] iParms)
{
using (IDbConnection iConn = this.GetConnection())
{
IDbCommand iCmd = GetCommand();
{
try
{
PrepareCommand(out iCmd, iConn, null, SQLString, iParms);
int rows = iCmd.ExecuteNonQuery();
iCmd.Parameters.Clear();
return rows;
}
catch (System.Exception E)
{
throw new Exception(E.Message);
}
finally
{
iCmd.Dispose();
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的哈希表(key為sql語句,value是該語句的SqlParameter[])</param>
public void ExecuteSqlTran(Hashtable SQLStringList)
{
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
using (IDbTransaction iTrans = iConn.BeginTransaction())
{
IDbCommand iCmd = GetCommand();
try
{
//循環
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
IDataParameter[] iParms = (IDataParameter[])myDE.Value;
PrepareCommand(out iCmd, iConn, iTrans, cmdText, iParms);
int val = iCmd.ExecuteNonQuery();
iCmd.Parameters.Clear();
}
iTrans.Commit();
}
catch
{
iTrans.Rollback();
throw;
}
finally
{
iCmd.Dispose();
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public object GetSingle(string SQLString, params IDataParameter[] iParms)
{
using (IDbConnection iConn = this.GetConnection())
{
IDbCommand iCmd = GetCommand();
{
try
{
PrepareCommand(out iCmd, iConn, null, SQLString, iParms);
object obj = iCmd.ExecuteScalar();
iCmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
iCmd.Dispose();
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行查詢語句,返回IDataReader
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns> IDataReader </returns>
public IDataReader ExecuteReader(string SQLString, params IDataParameter[] iParms)
{
IDbConnection iConn = this.GetConnection();
{
IDbCommand iCmd = GetCommand();
{
try
{
PrepareCommand(out iCmd, iConn, null, SQLString, iParms);
System.Data.IDataReader iReader = iCmd.ExecuteReader();
iCmd.Parameters.Clear();
return iReader;
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
finally
{
iCmd.Dispose();
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataSet</returns>
public DataSet Query(string sqlString, params IDataParameter[] iParms)
{
using (IDbConnection iConn = this.GetConnection())
{
IDbCommand iCmd = GetCommand();
{
PrepareCommand(out iCmd, iConn, null, sqlString, iParms);
try
{
IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
DataSet ds = new DataSet();
iAdapter.Fill(ds);
iCmd.Parameters.Clear();
return ds;
}
catch (System.Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
iCmd.Dispose();
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
}
}
}

/// <summary>
/// 初始化Command
/// </summary>
/// <param name="iCmd"></param>
/// <param name="iConn"></param>
/// <param name="iTrans"></param>
/// <param name="cmdText"></param>
/// <param name="iParms"></param>
private void PrepareCommand(out IDbCommand iCmd, IDbConnection iConn, System.Data.IDbTransaction iTrans, string cmdText, IDataParameter[] iParms)
{
if (iConn.State != ConnectionState.Open)
iConn.Open();
iCmd = this.GetCommand();
iCmd.Connection = iConn;
iCmd.CommandText = cmdText;
if (iTrans != null)
iCmd.Transaction = iTrans;
iCmd.CommandType = CommandType.Text;//cmdType;
if (iParms != null)
{
foreach (IDataParameter parm in iParms)
iCmd.Parameters.Add(parm);
}
}
#endregion

#region 存儲過程操作
/// <summary>
/// 執行存儲過程
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <returns>SqlDataReader</returns>
public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
IDbConnection iConn = this.GetConnection();
{
iConn.Open();

using (SqlCommand sqlCmd = BuildQueryCommand(iConn, storedProcName, parameters))
{
return sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
}

/// <summary>
/// 執行存儲過程
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <param name="tableName">DataSet結果中的表名</param>
/// <returns>DataSet</returns>
public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (IDbConnection iConn = this.GetConnection())
{
DataSet dataSet = new DataSet();
iConn.Open();
IDataAdapter iDA = this.GetAdapater();
iDA = this.GetAdapater(BuildQueryCommand(iConn, storedProcName, parameters));
((SqlDataAdapter)iDA).Fill(dataSet, tableName);
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
return dataSet;
}
}

/// <summary>
/// 執行存儲過程
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <param name="tableName">DataSet結果中的表名</param>
/// <param name="startIndex">開始記錄索引</param>
/// <param name="pageSize">頁面記錄大小</param>
/// <returns>DataSet</returns>
public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, int startIndex, int pageSize, string tableName)
{
using (IDbConnection iConn = this.GetConnection())
{
DataSet dataSet = new DataSet();
iConn.Open();
IDataAdapter iDA = this.GetAdapater();
iDA = this.GetAdapater(BuildQueryCommand(iConn, storedProcName, parameters));

((SqlDataAdapter)iDA).Fill(dataSet, startIndex, pageSize, tableName);
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
return dataSet;
}
}

/// <summary>
/// 執行存儲過程 填充已經存在的DataSet數據集
/// </summary>
/// <param name="storeProcName">存儲過程名稱</param>
/// <param name="parameters">存儲過程參數</param>
/// <param name="dataSet">要填充的數據集</param>
/// <param name="tablename">要填充的表名</param>
/// <returns></returns>
public DataSet RunProcedure(string storeProcName, IDataParameter[] parameters, DataSet dataSet, string tableName)
{
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
IDataAdapter iDA = this.GetAdapater();
iDA = this.GetAdapater(BuildQueryCommand(iConn, storeProcName, parameters));

((SqlDataAdapter)iDA).Fill(dataSet, tableName);

if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
return dataSet;
}
}

/// <summary>
/// 執行存儲過程並返回受影響的行數
/// </summary>
/// <param name="storedProcName"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public int RunProcedureNoQuery(string storedProcName, IDataParameter[] parameters)
{
int result = 0;
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
using (SqlCommand scmd = BuildQueryCommand(iConn, storedProcName, parameters))
{
result = scmd.ExecuteNonQuery();
}

if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
return result;
}

public string RunProcedureExecuteScalar(string storeProcName, IDataParameter[] parameters)
{
string result = string.Empty;
using (IDbConnection iConn = this.GetConnection())
{
iConn.Open();
using (SqlCommand scmd = BuildQueryCommand(iConn, storeProcName, parameters))
{
object obj = scmd.ExecuteScalar();
if (obj == null)
result = null;
else
result = obj.ToString();
}
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
}
return result;
}

/// <summary>
/// 構建 SqlCommand 對象(用來返回一個結果集,而不是一個整數值)
/// </summary>
/// <param name="connection">數據庫連接</param>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <returns>SqlCommand</returns>
private SqlCommand BuildQueryCommand(IDbConnection iConn, string storedProcName, IDataParameter[] parameters)
{
IDbCommand iCmd = GetCommand(storedProcName, iConn);
iCmd.CommandType = CommandType.StoredProcedure;
if (parameters == null)
{
return (SqlCommand)iCmd;
}
foreach (IDataParameter parameter in parameters)
{
iCmd.Parameters.Add(parameter);
}
return (SqlCommand)iCmd;
}

/// <summary>
/// 執行存儲過程,返回影響的行數
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <param name="rowsAffected">影響的行數</param>
/// <returns></returns>
public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
using (IDbConnection iConn = this.GetConnection())
{
int result;
iConn.Open();
using (SqlCommand sqlCmd = BuildIntCommand(iConn, storedProcName, parameters))
{
rowsAffected = sqlCmd.ExecuteNonQuery();
result = (int)sqlCmd.Parameters["ReturnValue"].Value;
if (iConn.State != ConnectionState.Closed)
{
iConn.Close();
}
return result;
}
}
}

/// <summary>
/// 創建 SqlCommand 對象實例(用來返回一個整數值)
/// </summary>
/// <param name="storedProcName">存儲過程名</param>
/// <param name="parameters">存儲過程參數</param>
/// <returns>SqlCommand 對象實例</returns>
private SqlCommand BuildIntCommand(IDbConnection iConn, string storedProcName, IDataParameter[] parameters)
{
SqlCommand sqlCmd = BuildQueryCommand(iConn, storedProcName, parameters);
sqlCmd.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return sqlCmd;
}
#endregion
}
}

小注: 這個類封裝成dll後,相關數據庫連接可在,引用該dll項目的app.config文件中寫,如果是web程序,這需要修改代碼,將構造函數中獲取app.config的信息換成獲取web.config的信息。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved