在.NET平臺中,C#語言一般使用ADO.NET組件來操作Sqlserver資料庫,通過ADO.NET組件可以實現連接資料庫、查詢數據集、執行SQL語句以及關閉資料庫連接等操作,為此網上有很多開發者自定義封裝好的SqlHelper類供使用,其實微軟官方自己也提供了一個比較完整的Sqlserver數據 ...
在.NET平臺中,C#語言一般使用ADO.NET組件來操作Sqlserver資料庫,通過ADO.NET組件可以實現連接資料庫、查詢數據集、執行SQL語句以及關閉資料庫連接等操作,為此網上有很多開發者自定義封裝好的SqlHelper類供使用,其實微軟官方自己也提供了一個比較完整的Sqlserver資料庫操作幫助類SqlHelper,該幫助類文件中包含了詳細的中文註釋。
該SqlHelper類比較完整,代碼量比較多,因此博主加了個鏈接提供個讀者下載,百度網盤下載地址:SqlHelper類。
備註:此文章轉載自微軟官方提供的Sqlserver資料庫操作幫助類SQLHelper類_IT技術小趣屋。
具體微軟官方幫助類實現如下:
using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collections; namespace Book.DAL { /// <summary> /// SqlServer數據訪問幫助類 /// </summary> public sealed class SqlHelper { #region 私有構造函數和方法 private SqlHelper() {} /// <summary> /// 將SqlParameter參數數組(參數值)分配給SqlCommand命令. /// 這個方法將給任何一個參數分配DBNull.Value; /// 該操作將阻止預設值的使用. /// </summary> /// <param>命令名</param> /// <param>SqlParameters數組</param> 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); } } } } /// <summary> /// 將DataRow類型的列值分配到SqlParameter參數數組. /// </summary> /// <param>要分配值的SqlParameter參數數組</param> /// <param>將要分配給存儲過程參數的DataRow</param> 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++; } } /// <summary> /// 將一個對象數組分配給SqlParameter參數數組. /// </summary> /// <param>要分配值的SqlParameter參數數組</param> /// <param>將要分配給存儲過程參數的對象數組</param> 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]; } } } /// <summary> /// 預處理用戶提供的命令,資料庫連接/事務/命令類型/參數 /// </summary> /// <param>要處理的SqlCommand</param> /// <param>資料庫連接</param> /// <param>一個有效的事務或者是null值</param> /// <param>命令類型 (存儲過程,命令文本, 其它.)</param> /// <param>存儲過程名或都T-SQL命令文本</param> /// <param>和命令相關聯的SqlParameter參數數組,如果沒有參數為'null'</param> /// <param><c>true</c> 如果連接是打開的,則為true,其它情況下為false.</param> 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 ExecuteNonQuery命令 /// <summary> /// 執行指定連接字元串,類型的SqlCommand. /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param>一個有效的資料庫連接字元串</param> /// <param>命令類型 (存儲過程,命令文本, 其它.)</param> /// <param>存儲過程名稱或SQL語句</param> /// <returns>返回命令影響的行數</returns> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText) { return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 執行指定連接字元串,類型的SqlCommand.如果沒有提供參數,不返回結果. /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param>一個有效的資料庫連接字元串</param> /// <param>命令類型 (存儲過程,命令文本, 其它.)</param> /// <param>存儲過程名稱或SQL語句</param> /// <param>SqlParameter參數數組</param> /// <returns>返回命令影響的行數</returns> 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); } } /// <summary> /// 執行指定連接字元串的存儲過程,將對象數組的值賦給存儲過程參數, /// 此方法需要在參數緩存方法中探索參數並生成參數. /// </summary> /// <remarks> /// 這個方法沒有提供訪問輸出參數和返回值. /// 示例: /// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36); /// </remarks> /// <param>一個有效的資料庫連接字元串/param> /// <param>存儲過程名稱</param> /// <param>分配到存儲過程輸入參數的對象數組</param> /// <returns>返回受影響的行數</returns> 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); } } /// <summary> /// 執行指定資料庫連接對象的命令 /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>命令類型(存儲過程,命令文本或其它.)</param> /// <param>存儲過程名稱或T-SQL語句</param> /// <returns>返回影響的行數</returns> public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText) { return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 執行指定資料庫連接對象的命令 /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>命令類型(存儲過程,命令文本或其它.)</param> /// <param>T存儲過程名稱或T-SQL語句</param> /// <param>SqlParamter參數數組</param> /// <returns>返回影響的行數</returns> 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; } /// <summary> /// 執行指定資料庫連接對象的命令,將對象數組的值賦給存儲過程參數. /// </summary> /// <remarks> /// 此方法不提供訪問存儲過程輸出參數和返回值 /// 示例: /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>存儲過程名</param> /// <param>分配給存儲過程輸入參數的對象數組</param> /// <returns>返回影響的行數</returns> 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); } } /// <summary> /// 執行帶事務的SqlCommand. /// </summary> /// <remarks> /// 示例.: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>命令類型(存儲過程,命令文本或其它.)</param> /// <param>存儲過程名稱或T-SQL語句</param> /// <returns>返回影響的行數/returns> public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText) { return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 執行帶事務的SqlCommand(指定參數). /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>命令類型(存儲過程,命令文本或其它.)</param> /// <param>存儲過程名稱或T-SQL語句</param> /// <param>SqlParamter參數數組</param> /// <returns>返回影響的行數</returns> 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; } /// <summary> /// 執行帶事務的SqlCommand(指定參數值). /// </summary> /// <remarks> /// 此方法不提供訪問存儲過程輸出參數和返回值 /// 示例: /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>存儲過程名</param> /// <param>分配給存儲過程輸入參數的對象數組</param> /// <returns>返回受影響的行數</returns> 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方法 /// <summary> /// 執行指定資料庫連接字元串的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param>一個有效的資料庫連接字元串</param> /// <param>命令類型 (存儲過程,命令文本或其它)</param> /// <param>存儲過程名稱或T-SQL語句</param> /// <returns>返回一個包含結果集的DataSet</returns> public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText) { return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 執行指定資料庫連接字元串的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param>一個有效的資料庫連接字元串</param> /// <param>命令類型 (存儲過程,命令文本或其它)</param> /// <param>存儲過程名稱或T-SQL語句</param> /// <param>SqlParamters參數數組</param> /// <returns>返回一個包含結果集的DataSet</returns> 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); } } /// <summary> /// 執行指定資料庫連接字元串的命令,直接提供參數值,返回DataSet. /// </summary> /// <remarks> /// 此方法不提供訪問存儲過程輸出參數和返回值. /// 示例: /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36); /// </remarks> /// <param>一個有效的資料庫連接字元串</param> /// <param>存儲過程名</param> /// <param>分配給存儲過程輸入參數的對象數組</param> /// <returns>返回一個包含結果集的DataSet</returns> 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); } } /// <summary> /// 執行指定資料庫連接對象的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param>一個有效的資料庫連接對象</param> /// <param>命令類型 (存儲過程,命令文本或其它)</param> /// <param>存儲過程名或T-SQL語句</param> /// <returns>返回一個包含結果集的DataSet</returns> public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText) { return ExecuteDataset(connection, commandType, commandText, (