Sql Server在.net中的資料訪問輔助類

大可山發表於2009-01-06

// =================================================================
// SqlServer資料訪問幫助類
// =================================================================

using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;

namespace BrawDraw.Com.Utility
{
 ///


 /// SqlServer資料訪問幫助類
 ///

    public sealed class SqlHelper
    {
        #region 私有建構函式和方法

  private SqlHelper() {}

        ///


        /// 將SqlParameter引數陣列(引數值)分配給SqlCommand命令.
        /// 這個方法將給任何一個引數分配DBNull.Value;
        /// 該操作將阻止預設值的使用.
        ///

        /// 命令名
        /// SqlParameters陣列
        private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
        {
   if( command == null ) throw new ArgumentNullException( "command" );
   if( commandParameters != null )
   {
    foreach (SqlParameter p in commandParameters)
    {
     if( p != null )
     {
      // 檢查未分配值的輸出引數,將其分配以DBNull.Value.
      if ( ( p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input ) &&
       (p.Value == null))
      {
       p.Value = DBNull.Value;
      }
      command.Parameters.Add(p);
     }
    }
   }
        }

        ///


        /// 將DataRow型別的列值分配到SqlParameter引數陣列.
        ///

        /// 要分配值的SqlParameter引數陣列
        /// 將要分配給儲存過程引數的DataRow
        private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
        {
            if ((commandParameters == null) || (dataRow == null))
            {
                return;
            }

   int i = 0;
            // 設定引數值
            foreach(SqlParameter commandParameter in commandParameters)
            {
    // 建立引數名稱,如果不存在,只丟擲一個異常.
    if( commandParameter.ParameterName == null ||
     commandParameter.ParameterName.Length <= 1 )
     throw new Exception(
      string.Format("請提供引數{0}一個有效的名稱{1}.", i, commandParameter.ParameterName ) );
                // 從dataRow的表中獲取為引數陣列中陣列名稱的列的索引.
    // 如果存在和引數名稱相同的列,則將列值賦給當前名稱的引數.
    if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
                    commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
    i++;
            }
        }

        ///


        /// 將一個物件陣列分配給SqlParameter引數陣列.
        ///

        /// 要分配值的SqlParameter引數陣列
        /// 將要分配給儲存過程引數的物件陣列
        private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
        {
            if ((commandParameters == null) || (parameterValues == null))
            {
                return;
            }

            // 確保物件陣列個數與引數個數匹配,如果不匹配,丟擲一個異常.
            if (commandParameters.Length != parameterValues.Length)
            {
                throw new ArgumentException("引數值個數與引數不匹配.");
            }

            // 給引數賦值
            for (int i = 0, j = commandParameters.Length; i < j; i++)
            {
                // If the current array value derives from IDbDataParameter, then assign its Value property
    if (parameterValues[i] is IDbDataParameter)
    {
     IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
     if( paramInstance.Value == null )
     {
      commandParameters[i].Value = DBNull.Value;
     }
     else
     {
      commandParameters[i].Value = paramInstance.Value;
     }
    }
    else if (parameterValues[i] == null)
    {
     commandParameters[i].Value = DBNull.Value;
    }
    else
    {
     commandParameters[i].Value = parameterValues[i];
    }
            }
        }

        ///


        /// 預處理使用者提供的命令,資料庫連線/事務/命令型別/引數
        ///

        /// 要處理的SqlCommand
        /// 資料庫連線
        /// 一個有效的事務或者是null值
        /// 命令型別 (儲存過程,命令文字, 其它.)
        /// 儲存過程名或都T-SQL命令文字
        /// 和命令相關聯的SqlParameter引數陣列,如果沒有引數為'null'
        /// true 如果連線是開啟的,則為true,其它情況下為false.
        private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection )
        {
   if( command == null ) throw new ArgumentNullException( "command" );
   if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" );

            // If the provided connection is not open, we will open it
   if (connection.State != ConnectionState.Open)
   {
    mustCloseConnection = true;
    connection.Open();
   }
   else
   {
    mustCloseConnection = false;
   }

            // 給命令分配一個資料庫連線.
            command.Connection = connection;

            // 設定命令文字(儲存過程名或SQL語句)
            command.CommandText = commandText;

            // 分配事務
            if (transaction != null)
            {
    if( transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
                command.Transaction = transaction;
            }

            // 設定命令型別.
            command.CommandType = commandType;

            // 分配命令引數
            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }
            return;
        }

        #endregion 私有建構函式和方法結束

  #region RunProcedure 返回查詢的引數
  ///


  /// 執行儲存過程,返回影響的行數 
  ///

  /// 儲存過程名
  /// 儲存過程引數
  /// 影響的行數
  ///
  public static int RunProcedure(string connectionString,string storedProcName,IDataParameter[] parameters)
  {
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
    int result;
    connection.Open();
    SqlCommand command = new SqlCommand(storedProcName,connection);
    command.CommandType = CommandType.StoredProcedure;
    if(parameters!=null&&parameters.Length>0)
    {
     foreach (SqlParameter parameter in parameters)
     {
      command.Parameters.Add( parameter );
     }
    }
    command.Parameters.Add( new SqlParameter ( "ReturnValue",
     SqlDbType.Int,4,ParameterDirection.ReturnValue,
     false,0,0,string.Empty,DataRowVersion.Default,null ));
    command.ExecuteNonQuery();
    result = (int)command.Parameters["ReturnValue"].Value;
    return result;
   }
  }
 

  #endregion

        #region ExecuteNonQuery命令

        ///


        /// 執行指定連線字串,型別的SqlCommand.
        ///

        ///
        /// 示例: 
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
        ///

        /// 一個有效的資料庫連線字串
        /// 命令型別 (儲存過程,命令文字, 其它.)
        /// 儲存過程名稱或SQL語句
        /// 返回命令影響的行數
        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        ///


        /// 執行指定連線字串,型別的SqlCommand.如果沒有提供引數,不返回結果.
        ///

        ///
        /// 示例: 
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        ///

        /// 一個有效的資料庫連線字串
        /// 命令型別 (儲存過程,命令文字, 其它.)
        /// 儲存過程名稱或SQL語句
        /// SqlParameter引數陣列
        /// 返回命令影響的行數
        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
   if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
            }
        }

        ///


        /// 執行指定連線字串的儲存過程,將物件陣列的值賦給儲存過程引數,
        /// 此方法需要在引數快取方法中探索引數並生成引數.
        ///

        ///
        /// 這個方法沒有提供訪問輸出引數和返回值.
        /// 示例: 
        ///  int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
        ///

        /// 一個有效的資料庫連線字串/param>
        /// 儲存過程名稱
        /// 分配到儲存過程輸入引數的物件陣列
        /// 返回受影響的行數
        public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
        {
   if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

            // 如果存在引數值
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                // 從探索儲存過程引數(載入到快取)並分配給儲存過程引數陣列.
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                // 給儲存過程引數賦值
                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
    // 沒有引數情況下
                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        ///


        /// 執行指定資料庫連線物件的命令
        ///

        ///
        /// 示例: 
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
        ///

        /// 一個有效的資料庫連線物件
        /// 命令型別(儲存過程,命令文字或其它.)
        /// 儲存過程名稱或T-SQL語句
        /// 返回影響的行數
        public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
        }

        ///


        /// 執行指定資料庫連線物件的命令
        ///

        ///
        /// 示例: 
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        ///

        /// 一個有效的資料庫連線物件
        /// 命令型別(儲存過程,命令文字或其它.)
        /// T儲存過程名稱或T-SQL語句
        /// SqlParamter引數陣列
        /// 返回影響的行數
        public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
   if( connection == null ) throw new ArgumentNullException( "connection" );

            // 建立SqlCommand命令,並進行預處理
            SqlCommand cmd = new SqlCommand();
   bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
     
            // Finally, execute the command
            int retval = cmd.ExecuteNonQuery();
     
            // 清除引數,以便再次使用.
            cmd.Parameters.Clear();
   if( mustCloseConnection )
    connection.Close();
            return retval;
        }

        ///


        /// 執行指定資料庫連線物件的命令,將物件陣列的值賦給儲存過程引數.
        ///

        ///
        /// 此方法不提供訪問儲存過程輸出引數和返回值
        /// 示例:  重點呼叫此方法
        ///  int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
        ///

        /// 一個有效的資料庫連線物件
        /// 儲存過程名
        /// 分配給儲存過程輸入引數的物件陣列
        /// 返回影響的行數
        public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
        {
   if( connection == null ) throw new ArgumentNullException( "connection" );
   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

            // 如果有引數值
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                // 從快取中載入儲存過程引數
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);

                // 給儲存過程分配引數值
                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
            }
        }

        ///


        /// 執行帶事務的SqlCommand.
        ///

        ///
        /// 示例.: 
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
        ///

        /// 一個有效的資料庫連線物件
     /// 命令型別(儲存過程,命令文字或其它.)
        /// 儲存過程名稱或T-SQL語句
        /// 返回影響的行數/returns>
        public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
        }

        ///


        /// 執行帶事務的SqlCommand(指定引數).
        ///

        ///
        /// 示例: 
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        ///

        /// 一個有效的資料庫連線物件
        /// 命令型別(儲存過程,命令文字或其它.)
        /// 儲存過程名稱或T-SQL語句
        /// SqlParamter引數陣列
        /// 返回影響的行數
  public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  {
   if( transaction == null ) throw new ArgumentNullException( "transaction" );
   if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );

   // 預處理
   SqlCommand cmd = new SqlCommand();
   bool mustCloseConnection = false;
   PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
      
   // 執行
   int retval = cmd.ExecuteNonQuery();
      
   // 清除引數集,以便再次使用.
   cmd.Parameters.Clear();
   return retval;
  }

        ///


        /// 執行帶事務的SqlCommand(指定引數值).
        ///

        ///
        /// 此方法不提供訪問儲存過程輸出引數和返回值
        /// 示例: 
        ///  int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
        ///

        /// 一個有效的資料庫連線物件
        /// 儲存過程名
        /// 分配給儲存過程輸入引數的物件陣列
        /// 返回受影響的行數
        public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
   if( transaction == null ) throw new ArgumentNullException( "transaction" );
   if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

   // 如果有引數值
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                // 從快取中載入儲存過程引數,如果快取中不存在則從資料庫中檢索引數資訊並載入到快取中. ()
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                // 給儲存過程引數賦值
                AssignParameterValues(commandParameters, parameterValues);

                // 呼叫過載方法
                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
    // 沒有引數值
                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion ExecuteNonQuery方法結束

        #region ExecuteDataset方法

        ///


        /// 執行指定資料庫連線字串的命令,返回DataSet.
        ///

        ///
        /// 示例: 
        ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
        ///

        /// 一個有效的資料庫連線字串
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名稱或T-SQL語句
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        ///


        /// 執行指定資料庫連線字串的命令,返回DataSet.
        ///

        ///
        /// 示例:
        ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        ///

        /// 一個有效的資料庫連線字串
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名稱或T-SQL語句
        /// SqlParamters引數陣列
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
   if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );

            // 建立並開啟資料庫連線物件,操作完成釋放物件.
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // 呼叫指定資料庫連線字串過載方法.
                return ExecuteDataset(connection, commandType, commandText, commandParameters);
            }
        }

  ///


  /// 執行指定資料庫連線字串的命令,直接提供引數值,返回DataSet.
  ///

  ///
  /// 此方法不提供訪問儲存過程輸出引數和返回值.
        /// 示例:
        ///  DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
        ///

        /// 一個有效的資料庫連線字串
        /// 儲存過程名
        /// 分配給儲存過程輸入引數的物件陣列
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
        {
   if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
  
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                // 從快取中檢索儲存過程引數
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                // 給儲存過程引數分配值
                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        ///


        /// 執行指定資料庫連線物件的命令,返回DataSet.
        ///

        ///
        /// 示例: 
        ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
        ///

        /// 一個有效的資料庫連線物件
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
        }
 
        ///
        /// 執行指定資料庫連線物件的命令,指定儲存過程引數,返回DataSet.
        ///

        ///
        /// 示例: 
        ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        ///

        /// 一個有效的資料庫連線物件
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// SqlParamter引數陣列
        /// 返回一個包含結果集的DataSet
  public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  {
   if( connection == null ) throw new ArgumentNullException( "connection" );

   // 預處理
   SqlCommand cmd = new SqlCommand();
   bool mustCloseConnection = false;
   PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
      
   // 建立SqlDataAdapter和DataSet.
   using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
   {
    DataSet ds = new DataSet();

    // 填充DataSet.
    da.Fill(ds);
   
    cmd.Parameters.Clear();

    if( mustCloseConnection )
     connection.Close();

    return ds;
   }
  }
 
        ///


        /// 執行指定資料庫連線物件的命令,指定引數值,返回DataSet.
        ///

        ///
        /// 此方法不提供訪問儲存過程輸入引數和返回值.
        /// 示例.:  重點呼叫此方法
        ///  DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
        ///

        /// 一個有效的資料庫連線物件
        /// 儲存過程名
        /// 分配給儲存過程輸入引數的物件陣列
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
        {
   if( connection == null ) throw new ArgumentNullException( "connection" );
   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                // 比快取中載入儲存過程引數
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);

                // 給儲存過程引數分配值
                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
            }
        }

        ///


        /// 執行指定事務的命令,返回DataSet.
        ///

        ///
        /// 示例: 
        ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
        ///

        /// 事務
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
        }
 
        ///
        /// 執行指定事務的命令,指定引數,返回DataSet.
        ///

        ///
        /// 示例: 
        ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        ///

        /// 事務
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// SqlParamter引數陣列
        /// 返回一個包含結果集的DataSet
  public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  {
   if( transaction == null ) throw new ArgumentNullException( "transaction" );
   if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );

   // 預處理
   SqlCommand cmd = new SqlCommand();
   bool mustCloseConnection = false;
   PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
      
   // 建立 DataAdapter & DataSet
   using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
   {
    DataSet ds = new DataSet();
    da.Fill(ds);
    cmd.Parameters.Clear();
    return ds;
   }
  }
 
        ///


        /// 執行指定事務的命令,指定引數值,返回DataSet.
        ///

        ///
        /// 此方法不提供訪問儲存過程輸入引數和返回值.
        /// 示例.: 
        ///  DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
        ///

        /// 事務
        /// 儲存過程名
        /// 分配給儲存過程輸入引數的物件陣列
        /// 返回一個包含結果集的DataSet
        public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
   if( transaction == null ) throw new ArgumentNullException( "transaction" );
   if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );
  
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                // 從快取中載入儲存過程引數
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                // 給儲存過程引數分配值
                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion ExecuteDataset資料集命令結束
 
        #region ExecuteReader 資料閱讀器

        ///


        /// 列舉,標識資料庫連線是由SqlHelper提供還是由呼叫者提供
        ///

        private enum SqlConnectionOwnership
        {
            /// 由SqlHelper提供連線
            Internal,
            /// 由呼叫者提供連線
            External
        }

        ///


        /// 執行指定資料庫連線物件的資料閱讀器.
        ///

        ///
        /// 如果是SqlHelper開啟連線,當連線關閉DataReader也將關閉.
        /// 如果是呼叫都開啟連線,DataReader由呼叫都管理.
        ///

        /// 一個有效的資料庫連線物件
        /// 一個有效的事務,或者為 'null'
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// SqlParameters引數陣列,如果沒有引數則為'null'
        /// 標識資料庫連線物件是由呼叫者提供還是由SqlHelper提供
        /// 返回包含結果集的SqlDataReader
        private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
        {
   if( connection == null ) throw new ArgumentNullException( "connection" );

   bool mustCloseConnection = false;
            // 建立命令
            SqlCommand cmd = new SqlCommand();
   try
   {
    PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  
    // 建立資料閱讀器
    SqlDataReader dataReader;

    if (connectionOwnership == SqlConnectionOwnership.External)
    {
     dataReader = cmd.ExecuteReader();
    }
    else
    {
     dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    }
  
    // 清除引數,以便再次使用..
    // HACK: There is a problem here, the output parameter values are fletched
    // when the reader is closed, so if the parameters are detached from the command
    // then the SqlReader can磘 set its values.
    // When this happen, the parameters can磘 be used again in other command.
    bool canClear = true;
    foreach(SqlParameter commandParameter in cmd.Parameters)
    {
     if (commandParameter.Direction != ParameterDirection.Input)
      canClear = false;
    }
           
    if (canClear)
    {
     cmd.Parameters.Clear();
    }

    return dataReader;
   }
   catch
   {
    if( mustCloseConnection )
     connection.Close();
    throw;
   }
        }

        ///


        /// 執行指定資料庫連線字串的資料閱讀器.
        ///

        ///
        /// 示例: 
        ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
        ///

        /// 一個有效的資料庫連線字串
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// 返回包含結果集的SqlDataReader
        public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        ///


        /// 執行指定資料庫連線字串的資料閱讀器,指定引數.
        ///

        ///
        /// 示例: 
        ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        ///

        /// 一個有效的資料庫連線字串
        /// 命令型別 (儲存過程,命令文字或其它)
        /// 儲存過程名或T-SQL語句
        /// SqlParamter引數陣列(new SqlParameter("@prodid", 24))
        /// 返回包含結果集的SqlDataReader
        public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
   if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
            SqlConnection connection = null;
            try
            {
    connection = new SqlConnection(connectionString);
    connection.Open();

                return ExecuteReader(connection, null, commandType, commandText, commandParameters,SqlConnectionOwnership.Internal);
            }
            catch
            {
                // If we fail to return the SqlDatReader, we need to close the connection ourselves
                if( connection != null ) connection.Close();
                throw;
            }
           
        }

        ///


        /// 執行指定資料庫連線字串的資料閱讀器,指定引數值.
        ///

   &nb

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/14601556/viewspace-528474/,如需轉載,請註明出處,否則將追究法律責任。

相關文章