[轉MSDN]C#.NET操作資料庫通用類(MS SQL Server篇)

來源:互聯網
上載者:User

下面給出了一個C#操作MS SQL Server 資料庫的通用類,通過該類可以對資料庫進行任何操作,包括執行SQL語句、執行預存程序。以下是其詳細實現過程,希望大家共同修改最佳化之。稍後將介紹如何使用它實現N層的程式設計。

 

配置web.config檔案的連結參數

 

<appSettings>
    <!--
  connStr參數設定,案例說明:
  (1)Sql server資料庫,例如“server=local;database=test;uid=sa;pwd=;”
  (2)Access資料庫,例如“data\ex.mdb; user id='admin';Jet OLEDB:database password='admin';”
 -->
    <add key="connStr" value="server=127.0.0.1;database=DbName;uid=sa;pwd=;" />
  </appSettings>

 

C#代碼

 

using System;
using System.Data;
using System.Data.SqlClient;

namespace Com.LXJ.Database
{
 /// <summary>
 /// ConnDB 的摘要說明。
 /// </summary>
 public class ConnDB
 {
  protected SqlConnection Connection;
  private string connectionString;

  /// <summary>
  /// 預設建構函式
  /// </summary>
  public ConnDB()
  {
   string connStr;
   connStr = System.Configuration.ConfigurationSettings.AppSettings["connStr"].ToString();

   connectionString = connStr;
   Connection = new SqlConnection(connectionString);
  }

  /// <summary>
  /// 帶參數的建構函式
  /// </summary>
  /// <param name="newConnectionString">資料庫聯結字串</param>
  public ConnDB(string newConnectionString)
  {
   connectionString = newConnectionString;
   Connection = new SqlConnection(connectionString);
  }

  /// <summary>
  /// 完成SqlCommand對象的執行個體化
  /// </summary>
  /// <param name="storedProcName"></param>
  /// <param name="parameters"></param>
  /// <returns></returns>
  private SqlCommand BuildCommand(string storedProcName,IDataParameter[] parameters)
  {
   SqlCommand command = BuildQueryCommand(storedProcName,parameters);
   command.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4,ParameterDirection.ReturnValue,false,0,0,string.Empty,DataRowVersion.Default,null));
   return command;
  }

  /// <summary>
  /// 建立新的SQL命令對象(預存程序)
  /// </summary>
  /// <param name="storedProcName"></param>
  /// <param name="parameters"></param>
  /// <returns></returns>
  private SqlCommand BuildQueryCommand(string storedProcName,IDataParameter[] parameters)
  {
   SqlCommand command = new SqlCommand(storedProcName,Connection);
   command.CommandType = CommandType.StoredProcedure;
   foreach (SqlParameter parameter in parameters)
   {
    command.Parameters.Add(parameter);
   }
   return command;
  }

  /// <summary>
  /// 執行預存程序,無傳回值
  /// </summary>
  /// <param name="storedProcName"></param>
  /// <param name="parameters"></param>
  public void ExecuteProcedure(string storedProcName,IDataParameter[] parameters)
  {
   Connection.Open();
   SqlCommand command;
   command=BuildQueryCommand(storedProcName,parameters);
   command.ExecuteNonQuery();
   Connection.Close();
  }

  /// <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)
  {
   int result;
   Connection.Open();
   SqlCommand command = BuildCommand(storedProcName,parameters);
   rowsAffected = command.ExecuteNonQuery();
   result = (int)command.Parameters["ReturnValue"].Value;
   Connection.Close();

   return result;
  }
  

  /// <summary>
  /// 重載RunProcedure把執行預存程序的結果放在SqlDataReader中
  /// </summary>
  /// <param name="storedProcName"></param>
  /// <param name="parameters"></param>
  /// <returns></returns>
  public SqlDataReader RunProcedure(string storedProcName,IDataParameter[] parameters)
  {
   SqlDataReader returnReader;
   Connection.Open();
   SqlCommand command = BuildQueryCommand(storedProcName,parameters);
   command.CommandType = CommandType.StoredProcedure;
   returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
   return returnReader;
  }

  /// <summary>
  /// 重載RunProcedure把執行預存程序的結果儲存在DataSet中和表tableName為選擇性參數
  /// </summary>
  /// <param name="storedProcName"></param>
  /// <param name="parameters"></param>
  /// <param name="tableName"></param>
  /// <returns></returns>
  public DataSet RunProcedure(string storedProcName,IDataParameter[] parameters,params string[] tableName)
  {
   DataSet dataSet = new DataSet();
   Connection.Open();
   SqlDataAdapter sqlDA = new SqlDataAdapter();
   sqlDA.SelectCommand = BuildQueryCommand(storedProcName,parameters);
   string flag;
   flag = "";
   for(int i=0;i<tableName.Length;i++)
    flag = tableName[i];
   if (flag!="")
    sqlDA.Fill(dataSet,tableName[0]);
   else
    sqlDA.Fill(dataSet);
   Connection.Close();
   return dataSet;
  }

  
  /// <summary>
  /// 執行SQL語句,返回資料到DataSet中
  /// </summary>
  /// <param name="sql"></param>
  /// <returns></returns>
  public DataSet ReturnDataSet(string sql)
  {
   DataSet dataSet=new DataSet();
   Connection.Open();
   SqlDataAdapter sqlDA=new SqlDataAdapter(sql,Connection);
   sqlDA.Fill(dataSet,"objDataSet");
   Connection.Close();
   return dataSet;
  }
  

  /// <summary>
  /// 執行SQL語句,返回 DataReader
  /// </summary>
  /// <param name="sql"></param>
  /// <returns></returns>
  public SqlDataReader ReturnDataReader(String sql)
  {
   Connection.Open();
   SqlCommand command = new SqlCommand(sql,Connection);
   SqlDataReader dataReader = command.ExecuteReader();

   return dataReader;
  }

  /// <summary>
  /// 執行SQL語句,返回記錄數
  /// </summary>
  /// <param name="sql"></param>
  /// <returns></returns>
  public int ReturnRecordCount(string sql)
  {
   int recordCount = 0;

   Connection.Open();
   SqlCommand command = new SqlCommand(sql,Connection);
   SqlDataReader dataReader = command.ExecuteReader();

   while(dataReader.Read())
   {
    recordCount++;
   }
   dataReader.Close();
   Connection.Close();

   return recordCount;
  }

  /// <summary>
  /// 執行SQL語句
  /// </summary>
  /// <param name="sql"></param>
  /// <returns></returns>
  public bool EditDatabase(string sql)
  {
   bool successState = false;

   Connection.Open();
   SqlTransaction myTrans = Connection.BeginTransaction();
   SqlCommand command = new SqlCommand(sql,Connection,myTrans);
   try
   {
    command.ExecuteNonQuery();
    myTrans.Commit();
    successState = true;
   }
   catch
   {
    myTrans.Rollback();
   }
   finally
   {
    Connection.Close();
   }

   return successState;
  }

  /// <summary>
  /// 關閉資料庫聯結
  /// </summary>
  public void Close()
  {
   Connection.Close();
  }

 }//end class
}//end namespace

 

 稍後將介使用它實現N層設計的案例,在這之前您需要熟悉預存程序的知識

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.