1. 代码
  2.  
  3. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 // ===============================================================================
  4. // Microsoft Data Access Application Block for .NET
  5. // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
  6. //
  7. // SQLHelper.cs
  8. //
  9. // This file contains the implementations of the SqlHelper and SqlHelperParameterCache
  10. // classes.
  11. //
  12. // For more information see the Data Access Application Block Implementation Overview.
  13. // ===============================================================================
  14. // Release history
  15. // VERSION DESCRIPTION
  16. // 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods
  17. //
  18. // ===============================================================================
  19. // Copyright (C) 2000-2001 Microsoft Corporation
  20. // All rights reserved.
  21. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
  22. // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
  23. // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
  24. // FITNESS FOR A PARTICULAR PURPOSE.
  25. // ==============================================================================
  26.  
  27. using System;
  28. using System.Data;
  29. using System.Xml;
  30. using System.Data.SqlClient;
  31. using System.Collections;
  32.  
  33. namespace Microsoft.ApplicationBlocks.Data
  34. {
  35. /// <summary>
  36. /// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
  37. /// common uses of SqlClient
  38. /// </summary>
  39. public sealed class SqlHelper
  40. {
  41. #region private utility methods & constructors
  42.  
  43. // Since this class provides only static methods, make the default constructor private to prevent
  44. // instances from being created with "new SqlHelper()"
  45. private SqlHelper() {}
  46.  
  47. /// <summary>
  48. /// This method is used to attach array of SqlParameters to a SqlCommand.
  49. ///
  50. /// This method will assign a value of DbNull to any parameter with a direction of
  51. /// InputOutput and a value of null.
  52. ///
  53. /// This behavior will prevent default values from being used, but
  54. /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
  55. /// where the user provided no input value.
  56. /// </summary>
  57. /// <param name="command">The command to which the parameters will be added</param>
  58. /// <param name="commandParameters">An array of SqlParameters to be added to command</param>
  59. private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
  60. {
  61. if( command == null ) throw new ArgumentNullException( "command" );
  62. if( commandParameters != null )
  63. {
  64. foreach (SqlParameter p in commandParameters)
  65. {
  66. if( p != null )
  67. {
  68. // Check for derived output value with no value assigned
  69. if ( ( p.Direction == ParameterDirection.InputOutput ||
  70. p.Direction == ParameterDirection.Input ) &&
  71. (p.Value == null))
  72. {
  73. p.Value = DBNull.Value;
  74. }
  75. command.Parameters.Add(p);
  76. }
  77. }
  78. }
  79. }
  80.  
  81. /// <summary>
  82. /// This method assigns dataRow column values to an array of SqlParameters
  83. /// </summary>
  84. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  85. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
  86. private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
  87. {
  88. if ((commandParameters == null) || (dataRow == null))
  89. {
  90. // Do nothing if we get no data
  91. return;
  92. }
  93.  
  94. int i = ;
  95. // Set the parameters values
  96. foreach(SqlParameter commandParameter in commandParameters)
  97. {
  98. // Check the parameter name
  99. if( commandParameter.ParameterName == null ||
  100. commandParameter.ParameterName.Length <= )
  101. throw new Exception(
  102. string.Format(
  103. "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
  104. i, commandParameter.ParameterName ) );
  105. if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring()) != -)
  106. commandParameter.Value = dataRow[commandParameter.ParameterName.Substring()];
  107. i++;
  108. }
  109. }
  110.  
  111. /// <summary>
  112. /// This method assigns an array of values to an array of SqlParameters
  113. /// </summary>
  114. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  115. /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
  116. private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
  117. {
  118. if ((commandParameters == null) || (parameterValues == null))
  119. {
  120. // Do nothing if we get no data
  121. return;
  122. }
  123.  
  124. // We must have the same number of values as we pave parameters to put them in
  125. if (commandParameters.Length != parameterValues.Length)
  126. {
  127. throw new ArgumentException("Parameter count does not match Parameter Value count.");
  128. }
  129.  
  130. // Iterate through the SqlParameters, assigning the values from the corresponding position in the
  131. // value array
  132. for (int i = , j = commandParameters.Length; i < j; i++)
  133. {
  134. // If the current array value derives from IDbDataParameter, then assign its Value property
  135. if (parameterValues[i] is IDbDataParameter)
  136. {
  137. IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
  138. if( paramInstance.Value == null )
  139. {
  140. commandParameters[i].Value = DBNull.Value;
  141. }
  142. else
  143. {
  144. commandParameters[i].Value = paramInstance.Value;
  145. }
  146. }
  147. else if (parameterValues[i] == null)
  148. {
  149. commandParameters[i].Value = DBNull.Value;
  150. }
  151. else
  152. {
  153. commandParameters[i].Value = parameterValues[i];
  154. }
  155. }
  156. }
  157.  
  158. /// <summary>
  159. /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
  160. /// to the provided command
  161. /// </summary>
  162. /// <param name="command">The SqlCommand to be prepared</param>
  163. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  164. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  165. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  166. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  167. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  168. /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
  169. private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection )
  170. {
  171. if( command == null ) throw new ArgumentNullException( "command" );
  172. if( commandText == null || commandText.Length == ) throw new ArgumentNullException( "commandText" );
  173.  
  174. // If the provided connection is not open, we will open it
  175. if (connection.State != ConnectionState.Open)
  176. {
  177. mustCloseConnection = true;
  178. connection.Open();
  179. }
  180. else
  181. {
  182. mustCloseConnection = false;
  183. }
  184.  
  185. // Associate the connection with the command
  186. command.Connection = connection;
  187.  
  188. // Set the command text (stored procedure name or SQL statement)
  189. command.CommandText = commandText;
  190.  
  191. // If we were provided a transaction, assign it
  192. if (transaction != null)
  193. {
  194. if( transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  195. command.Transaction = transaction;
  196. }
  197.  
  198. // Set the command type
  199. command.CommandType = commandType;
  200.  
  201. // Attach the command parameters if they are provided
  202. if (commandParameters != null)
  203. {
  204. AttachParameters(command, commandParameters);
  205. }
  206. return;
  207. }
  208.  
  209. #endregion private utility methods & constructors
  210.  
  211. #region ExecuteNonQuery
  212.  
  213. /// <summary>
  214. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
  215. /// the connection string
  216. /// </summary>
  217. /// <remarks>
  218. /// e.g.:
  219. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
  220. /// </remarks>
  221. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  222. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  223. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  224. /// <returns>An int representing the number of rows affected by the command</returns>
  225. public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
  226. {
  227. // Pass through the call providing null for the set of SqlParameters
  228. return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
  229. }
  230.  
  231. /// <summary>
  232. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  233. /// using the provided parameters
  234. /// </summary>
  235. /// <remarks>
  236. /// e.g.:
  237. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  238. /// </remarks>
  239. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  240. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  241. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  242. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  243. /// <returns>An int representing the number of rows affected by the command</returns>
  244. public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  245. {
  246. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  247.  
  248. // Create & open a SqlConnection, and dispose of it after we are done
  249. using (SqlConnection connection = new SqlConnection(connectionString))
  250. {
  251. connection.Open();
  252.  
  253. // Call the overload that takes a connection in place of the connection string
  254. return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
  255. }
  256. }
  257.  
  258. /// <summary>
  259. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
  260. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  261. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  262. /// </summary>
  263. /// <remarks>
  264. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  265. ///
  266. /// e.g.:
  267. /// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
  268. /// </remarks>
  269. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  270. /// <param name="spName">The name of the stored prcedure</param>
  271. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  272. /// <returns>An int representing the number of rows affected by the command</returns>
  273. public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
  274. {
  275. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  276. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  277.  
  278. // If we receive parameter values, we need to figure out where they go
  279. if ((parameterValues != null) && (parameterValues.Length > ))
  280. {
  281. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  282. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  283.  
  284. // Assign the provided values to these parameters based on parameter order
  285. AssignParameterValues(commandParameters, parameterValues);
  286.  
  287. // Call the overload that takes an array of SqlParameters
  288. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  289. }
  290. else
  291. {
  292. // Otherwise we can just call the SP without params
  293. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
  294. }
  295. }
  296.  
  297. /// <summary>
  298. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
  299. /// </summary>
  300. /// <remarks>
  301. /// e.g.:
  302. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
  303. /// </remarks>
  304. /// <param name="connection">A valid SqlConnection</param>
  305. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  306. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  307. /// <returns>An int representing the number of rows affected by the command</returns>
  308. public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
  309. {
  310. // Pass through the call providing null for the set of SqlParameters
  311. return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
  312. }
  313.  
  314. /// <summary>
  315. /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
  316. /// using the provided parameters.
  317. /// </summary>
  318. /// <remarks>
  319. /// e.g.:
  320. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  321. /// </remarks>
  322. /// <param name="connection">A valid SqlConnection</param>
  323. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  324. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  325. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  326. /// <returns>An int representing the number of rows affected by the command</returns>
  327. public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  328. {
  329. if( connection == null ) throw new ArgumentNullException( "connection" );
  330.  
  331. // Create a command and prepare it for execution
  332. SqlCommand cmd = new SqlCommand();
  333. bool mustCloseConnection = false;
  334. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
  335.  
  336. // Finally, execute the command
  337. int retval = cmd.ExecuteNonQuery();
  338.  
  339. // Detach the SqlParameters from the command object, so they can be used again
  340. cmd.Parameters.Clear();
  341. if( mustCloseConnection )
  342. connection.Close();
  343. return retval;
  344. }
  345.  
  346. /// <summary>
  347. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
  348. /// using the provided parameter values. This method will query the database to discover the parameters for the
  349. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  350. /// </summary>
  351. /// <remarks>
  352. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  353. ///
  354. /// e.g.:
  355. /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
  356. /// </remarks>
  357. /// <param name="connection">A valid SqlConnection</param>
  358. /// <param name="spName">The name of the stored procedure</param>
  359. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  360. /// <returns>An int representing the number of rows affected by the command</returns>
  361. public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
  362. {
  363. if( connection == null ) throw new ArgumentNullException( "connection" );
  364. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  365.  
  366. // If we receive parameter values, we need to figure out where they go
  367. if ((parameterValues != null) && (parameterValues.Length > ))
  368. {
  369. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  370. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  371.  
  372. // Assign the provided values to these parameters based on parameter order
  373. AssignParameterValues(commandParameters, parameterValues);
  374.  
  375. // Call the overload that takes an array of SqlParameters
  376. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  377. }
  378. else
  379. {
  380. // Otherwise we can just call the SP without params
  381. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
  382. }
  383. }
  384.  
  385. /// <summary>
  386. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
  387. /// </summary>
  388. /// <remarks>
  389. /// e.g.:
  390. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
  391. /// </remarks>
  392. /// <param name="transaction">A valid SqlTransaction</param>
  393. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  394. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  395. /// <returns>An int representing the number of rows affected by the command</returns>
  396. public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
  397. {
  398. // Pass through the call providing null for the set of SqlParameters
  399. return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
  400. }
  401.  
  402. /// <summary>
  403. /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
  404. /// using the provided parameters.
  405. /// </summary>
  406. /// <remarks>
  407. /// e.g.:
  408. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  409. /// </remarks>
  410. /// <param name="transaction">A valid SqlTransaction</param>
  411. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  412. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  413. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  414. /// <returns>An int representing the number of rows affected by the command</returns>
  415. public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  416. {
  417. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  418. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  419.  
  420. // Create a command and prepare it for execution
  421. SqlCommand cmd = new SqlCommand();
  422. bool mustCloseConnection = false;
  423. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  424.  
  425. // Finally, execute the command
  426. int retval = cmd.ExecuteNonQuery();
  427.  
  428. // Detach the SqlParameters from the command object, so they can be used again
  429. cmd.Parameters.Clear();
  430. return retval;
  431. }
  432.  
  433. /// <summary>
  434. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
  435. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  436. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  437. /// </summary>
  438. /// <remarks>
  439. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  440. ///
  441. /// e.g.:
  442. /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
  443. /// </remarks>
  444. /// <param name="transaction">A valid SqlTransaction</param>
  445. /// <param name="spName">The name of the stored procedure</param>
  446. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  447. /// <returns>An int representing the number of rows affected by the command</returns>
  448. public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
  449. {
  450. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  451. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  452. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  453.  
  454. // If we receive parameter values, we need to figure out where they go
  455. if ((parameterValues != null) && (parameterValues.Length > ))
  456. {
  457. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  458. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  459.  
  460. // Assign the provided values to these parameters based on parameter order
  461. AssignParameterValues(commandParameters, parameterValues);
  462.  
  463. // Call the overload that takes an array of SqlParameters
  464. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
  465. }
  466. else
  467. {
  468. // Otherwise we can just call the SP without params
  469. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
  470. }
  471. }
  472.  
  473. #endregion ExecuteNonQuery
  474.  
  475. #region ExecuteDataset
  476.  
  477. /// <summary>
  478. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  479. /// the connection string.
  480. /// </summary>
  481. /// <remarks>
  482. /// e.g.:
  483. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
  484. /// </remarks>
  485. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  486. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  487. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  488. /// <returns>A dataset containing the resultset generated by the command</returns>
  489. public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
  490. {
  491. // Pass through the call providing null for the set of SqlParameters
  492. return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
  493. }
  494.  
  495. /// <summary>
  496. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  497. /// using the provided parameters.
  498. /// </summary>
  499. /// <remarks>
  500. /// e.g.:
  501. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  502. /// </remarks>
  503. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  504. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  505. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  506. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  507. /// <returns>A dataset containing the resultset generated by the command</returns>
  508. public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  509. {
  510. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  511.  
  512. // Create & open a SqlConnection, and dispose of it after we are done
  513. using (SqlConnection connection = new SqlConnection(connectionString))
  514. {
  515. connection.Open();
  516.  
  517. // Call the overload that takes a connection in place of the connection string
  518. return ExecuteDataset(connection, commandType, commandText, commandParameters);
  519. }
  520. }
  521.  
  522. /// <summary>
  523. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  524. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  525. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  526. /// </summary>
  527. /// <remarks>
  528. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  529. ///
  530. /// e.g.:
  531. /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
  532. /// </remarks>
  533. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  534. /// <param name="spName">The name of the stored procedure</param>
  535. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  536. /// <returns>A dataset containing the resultset generated by the command</returns>
  537. public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
  538. {
  539. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  540. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  541.  
  542. // If we receive parameter values, we need to figure out where they go
  543. if ((parameterValues != null) && (parameterValues.Length > ))
  544. {
  545. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  546. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  547.  
  548. // Assign the provided values to these parameters based on parameter order
  549. AssignParameterValues(commandParameters, parameterValues);
  550.  
  551. // Call the overload that takes an array of SqlParameters
  552. return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  553. }
  554. else
  555. {
  556. // Otherwise we can just call the SP without params
  557. return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  558. }
  559. }
  560.  
  561. /// <summary>
  562. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  563. /// </summary>
  564. /// <remarks>
  565. /// e.g.:
  566. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
  567. /// </remarks>
  568. /// <param name="connection">A valid SqlConnection</param>
  569. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  570. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  571. /// <returns>A dataset containing the resultset generated by the command</returns>
  572. public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
  573. {
  574. // Pass through the call providing null for the set of SqlParameters
  575. return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
  576. }
  577.  
  578. /// <summary>
  579. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  580. /// using the provided parameters.
  581. /// </summary>
  582. /// <remarks>
  583. /// e.g.:
  584. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  585. /// </remarks>
  586. /// <param name="connection">A valid SqlConnection</param>
  587. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  588. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  589. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  590. /// <returns>A dataset containing the resultset generated by the command</returns>
  591. public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  592. {
  593. if( connection == null ) throw new ArgumentNullException( "connection" );
  594.  
  595. // Create a command and prepare it for execution
  596. SqlCommand cmd = new SqlCommand();
  597. bool mustCloseConnection = false;
  598. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
  599.  
  600. // Create the DataAdapter & DataSet
  601. using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
  602. {
  603. DataSet ds = new DataSet();
  604.  
  605. // Fill the DataSet using default values for DataTable names, etc
  606. da.Fill(ds);
  607.  
  608. // Detach the SqlParameters from the command object, so they can be used again
  609. cmd.Parameters.Clear();
  610.  
  611. if( mustCloseConnection )
  612. connection.Close();
  613.  
  614. // Return the dataset
  615. return ds;
  616. }
  617. }
  618.  
  619. /// <summary>
  620. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  621. /// using the provided parameter values. This method will query the database to discover the parameters for the
  622. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  623. /// </summary>
  624. /// <remarks>
  625. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  626. ///
  627. /// e.g.:
  628. /// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
  629. /// </remarks>
  630. /// <param name="connection">A valid SqlConnection</param>
  631. /// <param name="spName">The name of the stored procedure</param>
  632. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  633. /// <returns>A dataset containing the resultset generated by the command</returns>
  634. public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
  635. {
  636. if( connection == null ) throw new ArgumentNullException( "connection" );
  637. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  638.  
  639. // If we receive parameter values, we need to figure out where they go
  640. if ((parameterValues != null) && (parameterValues.Length > ))
  641. {
  642. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  643. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  644.  
  645. // Assign the provided values to these parameters based on parameter order
  646. AssignParameterValues(commandParameters, parameterValues);
  647.  
  648. // Call the overload that takes an array of SqlParameters
  649. return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  650. }
  651. else
  652. {
  653. // Otherwise we can just call the SP without params
  654. return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
  655. }
  656. }
  657.  
  658. /// <summary>
  659. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  660. /// </summary>
  661. /// <remarks>
  662. /// e.g.:
  663. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
  664. /// </remarks>
  665. /// <param name="transaction">A valid SqlTransaction</param>
  666. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  667. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  668. /// <returns>A dataset containing the resultset generated by the command</returns>
  669. public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
  670. {
  671. // Pass through the call providing null for the set of SqlParameters
  672. return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
  673. }
  674.  
  675. /// <summary>
  676. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  677. /// using the provided parameters.
  678. /// </summary>
  679. /// <remarks>
  680. /// e.g.:
  681. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  682. /// </remarks>
  683. /// <param name="transaction">A valid SqlTransaction</param>
  684. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  685. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  686. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  687. /// <returns>A dataset containing the resultset generated by the command</returns>
  688. public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  689. {
  690. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  691. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  692.  
  693. // Create a command and prepare it for execution
  694. SqlCommand cmd = new SqlCommand();
  695. bool mustCloseConnection = false;
  696. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  697.  
  698. // Create the DataAdapter & DataSet
  699. using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
  700. {
  701. DataSet ds = new DataSet();
  702.  
  703. // Fill the DataSet using default values for DataTable names, etc
  704. da.Fill(ds);
  705.  
  706. // Detach the SqlParameters from the command object, so they can be used again
  707. cmd.Parameters.Clear();
  708.  
  709. // Return the dataset
  710. return ds;
  711. }
  712. }
  713.  
  714. /// <summary>
  715. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  716. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  717. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  718. /// </summary>
  719. /// <remarks>
  720. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  721. ///
  722. /// e.g.:
  723. /// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
  724. /// </remarks>
  725. /// <param name="transaction">A valid SqlTransaction</param>
  726. /// <param name="spName">The name of the stored procedure</param>
  727. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  728. /// <returns>A dataset containing the resultset generated by the command</returns>
  729. public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
  730. {
  731. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  732. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  733. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  734.  
  735. // If we receive parameter values, we need to figure out where they go
  736. if ((parameterValues != null) && (parameterValues.Length > ))
  737. {
  738. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  739. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  740.  
  741. // Assign the provided values to these parameters based on parameter order
  742. AssignParameterValues(commandParameters, parameterValues);
  743.  
  744. // Call the overload that takes an array of SqlParameters
  745. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
  746. }
  747. else
  748. {
  749. // Otherwise we can just call the SP without params
  750. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
  751. }
  752. }
  753.  
  754. #endregion ExecuteDataset
  755.  
  756. #region ExecuteReader
  757.  
  758. /// <summary>
  759. /// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
  760. /// we can set the appropriate CommandBehavior when calling ExecuteReader()
  761. /// </summary>
  762. private enum SqlConnectionOwnership
  763. {
  764. /// <summary>Connection is owned and managed by SqlHelper</summary>
  765. Internal,
  766. /// <summary>Connection is owned and managed by the caller</summary>
  767. External
  768. }
  769.  
  770. /// <summary>
  771. /// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
  772. /// </summary>
  773. /// <remarks>
  774. /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
  775. ///
  776. /// If the caller provided the connection, we want to leave it to them to manage.
  777. /// </remarks>
  778. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  779. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  780. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  781. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  782. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  783. /// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
  784. /// <returns>SqlDataReader containing the results of the command</returns>
  785. private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
  786. {
  787. if( connection == null ) throw new ArgumentNullException( "connection" );
  788.  
  789. bool mustCloseConnection = false;
  790. // Create a command and prepare it for execution
  791. SqlCommand cmd = new SqlCommand();
  792. try
  793. {
  794. PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  795.  
  796. // Create a reader
  797. SqlDataReader dataReader;
  798.  
  799. // Call ExecuteReader with the appropriate CommandBehavior
  800. if (connectionOwnership == SqlConnectionOwnership.External)
  801. {
  802. dataReader = cmd.ExecuteReader();
  803. }
  804. else
  805. {
  806. dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  807. }
  808.  
  809. // Detach the SqlParameters from the command object, so they can be used again.
  810. // HACK: There is a problem here, the output parameter values are fletched
  811. // when the reader is closed, so if the parameters are detached from the command
  812. // then the SqlReader can磘 set its values.
  813. // When this happen, the parameters can磘 be used again in other command.
  814. bool canClear = true;
  815. foreach(SqlParameter commandParameter in cmd.Parameters)
  816. {
  817. if (commandParameter.Direction != ParameterDirection.Input)
  818. canClear = false;
  819. }
  820.  
  821. if (canClear)
  822. {
  823. cmd.Parameters.Clear();
  824. }
  825.  
  826. return dataReader;
  827. }
  828. catch
  829. {
  830. if( mustCloseConnection )
  831. connection.Close();
  832. throw;
  833. }
  834. }
  835.  
  836. /// <summary>
  837. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  838. /// the connection string.
  839. /// </summary>
  840. /// <remarks>
  841. /// e.g.:
  842. /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
  843. /// </remarks>
  844. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  845. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  846. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  847. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  848. public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
  849. {
  850. // Pass through the call providing null for the set of SqlParameters
  851. return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
  852. }
  853.  
  854. /// <summary>
  855. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  856. /// using the provided parameters.
  857. /// </summary>
  858. /// <remarks>
  859. /// e.g.:
  860. /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  861. /// </remarks>
  862. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  863. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  864. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  865. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  866. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  867. public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  868. {
  869. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  870. SqlConnection connection = null;
  871. try
  872. {
  873. connection = new SqlConnection(connectionString);
  874. connection.Open();
  875.  
  876. // Call the private overload that takes an internally owned connection in place of the connection string
  877. return ExecuteReader(connection, null, commandType, commandText, commandParameters,SqlConnectionOwnership.Internal);
  878. }
  879. catch
  880. {
  881. // If we fail to return the SqlDatReader, we need to close the connection ourselves
  882. if( connection != null ) connection.Close();
  883. throw;
  884. }
  885.  
  886. }
  887.  
  888. /// <summary>
  889. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  890. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  891. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  892. /// </summary>
  893. /// <remarks>
  894. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  895. ///
  896. /// e.g.:
  897. /// SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36);
  898. /// </remarks>
  899. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  900. /// <param name="spName">The name of the stored procedure</param>
  901. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  902. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  903. public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
  904. {
  905. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  906. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  907.  
  908. // If we receive parameter values, we need to figure out where they go
  909. if ((parameterValues != null) && (parameterValues.Length > ))
  910. {
  911. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  912.  
  913. AssignParameterValues(commandParameters, parameterValues);
  914.  
  915. return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  916. }
  917. else
  918. {
  919. // Otherwise we can just call the SP without params
  920. return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
  921. }
  922. }
  923.  
  924. /// <summary>
  925. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  926. /// </summary>
  927. /// <remarks>
  928. /// e.g.:
  929. /// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
  930. /// </remarks>
  931. /// <param name="connection">A valid SqlConnection</param>
  932. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  933. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  934. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  935. public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
  936. {
  937. // Pass through the call providing null for the set of SqlParameters
  938. return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
  939. }
  940.  
  941. /// <summary>
  942. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  943. /// using the provided parameters.
  944. /// </summary>
  945. /// <remarks>
  946. /// e.g.:
  947. /// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  948. /// </remarks>
  949. /// <param name="connection">A valid SqlConnection</param>
  950. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  951. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  952. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  953. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  954. public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  955. {
  956. // Pass through the call to the private overload using a null transaction value and an externally owned connection
  957. return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
  958. }
  959.  
  960. /// <summary>
  961. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  962. /// using the provided parameter values. This method will query the database to discover the parameters for the
  963. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  964. /// </summary>
  965. /// <remarks>
  966. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  967. ///
  968. /// e.g.:
  969. /// SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
  970. /// </remarks>
  971. /// <param name="connection">A valid SqlConnection</param>
  972. /// <param name="spName">The name of the stored procedure</param>
  973. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  974. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  975. public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
  976. {
  977. if( connection == null ) throw new ArgumentNullException( "connection" );
  978. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  979.  
  980. // If we receive parameter values, we need to figure out where they go
  981. if ((parameterValues != null) && (parameterValues.Length > ))
  982. {
  983. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  984.  
  985. AssignParameterValues(commandParameters, parameterValues);
  986.  
  987. return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  988. }
  989. else
  990. {
  991. // Otherwise we can just call the SP without params
  992. return ExecuteReader(connection, CommandType.StoredProcedure, spName);
  993. }
  994. }
  995.  
  996. /// <summary>
  997. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  998. /// </summary>
  999. /// <remarks>
  1000. /// e.g.:
  1001. /// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
  1002. /// </remarks>
  1003. /// <param name="transaction">A valid SqlTransaction</param>
  1004. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1005. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1006. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  1007. public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
  1008. {
  1009. // Pass through the call providing null for the set of SqlParameters
  1010. return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
  1011. }
  1012.  
  1013. /// <summary>
  1014. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  1015. /// using the provided parameters.
  1016. /// </summary>
  1017. /// <remarks>
  1018. /// e.g.:
  1019. /// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  1020. /// </remarks>
  1021. /// <param name="transaction">A valid SqlTransaction</param>
  1022. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1023. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1024. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1025. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  1026. public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1027. {
  1028. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1029. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1030.  
  1031. // Pass through to private overload, indicating that the connection is owned by the caller
  1032. return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
  1033. }
  1034.  
  1035. /// <summary>
  1036. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  1037. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1038. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1039. /// </summary>
  1040. /// <remarks>
  1041. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1042. ///
  1043. /// e.g.:
  1044. /// SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
  1045. /// </remarks>
  1046. /// <param name="transaction">A valid SqlTransaction</param>
  1047. /// <param name="spName">The name of the stored procedure</param>
  1048. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1049. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  1050. public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
  1051. {
  1052. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1053. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1054. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1055.  
  1056. // If we receive parameter values, we need to figure out where they go
  1057. if ((parameterValues != null) && (parameterValues.Length > ))
  1058. {
  1059. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1060.  
  1061. AssignParameterValues(commandParameters, parameterValues);
  1062.  
  1063. return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1064. }
  1065. else
  1066. {
  1067. // Otherwise we can just call the SP without params
  1068. return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
  1069. }
  1070. }
  1071.  
  1072. #endregion ExecuteReader
  1073.  
  1074. #region ExecuteScalar
  1075.  
  1076. /// <summary>
  1077. /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
  1078. /// the connection string.
  1079. /// </summary>
  1080. /// <remarks>
  1081. /// e.g.:
  1082. /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
  1083. /// </remarks>
  1084. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1085. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1086. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1087. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1088. public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
  1089. {
  1090. // Pass through the call providing null for the set of SqlParameters
  1091. return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
  1092. }
  1093.  
  1094. /// <summary>
  1095. /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string
  1096. /// using the provided parameters.
  1097. /// </summary>
  1098. /// <remarks>
  1099. /// e.g.:
  1100. /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1101. /// </remarks>
  1102. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1103. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1104. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1105. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1106. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1107. public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1108. {
  1109. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  1110. // Create & open a SqlConnection, and dispose of it after we are done
  1111. using (SqlConnection connection = new SqlConnection(connectionString))
  1112. {
  1113. connection.Open();
  1114.  
  1115. // Call the overload that takes a connection in place of the connection string
  1116. return ExecuteScalar(connection, commandType, commandText, commandParameters);
  1117. }
  1118. }
  1119.  
  1120. /// <summary>
  1121. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
  1122. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  1123. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1124. /// </summary>
  1125. /// <remarks>
  1126. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1127. ///
  1128. /// e.g.:
  1129. /// int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
  1130. /// </remarks>
  1131. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1132. /// <param name="spName">The name of the stored procedure</param>
  1133. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1134. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1135. public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
  1136. {
  1137. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  1138. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1139.  
  1140. // If we receive parameter values, we need to figure out where they go
  1141. if ((parameterValues != null) && (parameterValues.Length > ))
  1142. {
  1143. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1144. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  1145.  
  1146. // Assign the provided values to these parameters based on parameter order
  1147. AssignParameterValues(commandParameters, parameterValues);
  1148.  
  1149. // Call the overload that takes an array of SqlParameters
  1150. return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  1151. }
  1152. else
  1153. {
  1154. // Otherwise we can just call the SP without params
  1155. return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
  1156. }
  1157. }
  1158.  
  1159. /// <summary>
  1160. /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection.
  1161. /// </summary>
  1162. /// <remarks>
  1163. /// e.g.:
  1164. /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
  1165. /// </remarks>
  1166. /// <param name="connection">A valid SqlConnection</param>
  1167. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1168. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1169. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1170. public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
  1171. {
  1172. // Pass through the call providing null for the set of SqlParameters
  1173. return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
  1174. }
  1175.  
  1176. /// <summary>
  1177. /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
  1178. /// using the provided parameters.
  1179. /// </summary>
  1180. /// <remarks>
  1181. /// e.g.:
  1182. /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1183. /// </remarks>
  1184. /// <param name="connection">A valid SqlConnection</param>
  1185. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1186. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1187. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1188. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1189. public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1190. {
  1191. if( connection == null ) throw new ArgumentNullException( "connection" );
  1192.  
  1193. // Create a command and prepare it for execution
  1194. SqlCommand cmd = new SqlCommand();
  1195.  
  1196. bool mustCloseConnection = false;
  1197. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
  1198.  
  1199. // Execute the command & return the results
  1200. object retval = cmd.ExecuteScalar();
  1201.  
  1202. // Detach the SqlParameters from the command object, so they can be used again
  1203. cmd.Parameters.Clear();
  1204.  
  1205. if( mustCloseConnection )
  1206. connection.Close();
  1207.  
  1208. return retval;
  1209. }
  1210.  
  1211. /// <summary>
  1212. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
  1213. /// using the provided parameter values. This method will query the database to discover the parameters for the
  1214. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1215. /// </summary>
  1216. /// <remarks>
  1217. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1218. ///
  1219. /// e.g.:
  1220. /// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
  1221. /// </remarks>
  1222. /// <param name="connection">A valid SqlConnection</param>
  1223. /// <param name="spName">The name of the stored procedure</param>
  1224. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1225. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1226. public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
  1227. {
  1228. if( connection == null ) throw new ArgumentNullException( "connection" );
  1229. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1230.  
  1231. // If we receive parameter values, we need to figure out where they go
  1232. if ((parameterValues != null) && (parameterValues.Length > ))
  1233. {
  1234. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1235. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1236.  
  1237. // Assign the provided values to these parameters based on parameter order
  1238. AssignParameterValues(commandParameters, parameterValues);
  1239.  
  1240. // Call the overload that takes an array of SqlParameters
  1241. return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
  1242. }
  1243. else
  1244. {
  1245. // Otherwise we can just call the SP without params
  1246. return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
  1247. }
  1248. }
  1249.  
  1250. /// <summary>
  1251. /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction.
  1252. /// </summary>
  1253. /// <remarks>
  1254. /// e.g.:
  1255. /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
  1256. /// </remarks>
  1257. /// <param name="transaction">A valid SqlTransaction</param>
  1258. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1259. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1260. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1261. public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
  1262. {
  1263. // Pass through the call providing null for the set of SqlParameters
  1264. return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
  1265. }
  1266.  
  1267. /// <summary>
  1268. /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
  1269. /// using the provided parameters.
  1270. /// </summary>
  1271. /// <remarks>
  1272. /// e.g.:
  1273. /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1274. /// </remarks>
  1275. /// <param name="transaction">A valid SqlTransaction</param>
  1276. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1277. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1278. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1279. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1280. public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1281. {
  1282. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1283. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1284.  
  1285. // Create a command and prepare it for execution
  1286. SqlCommand cmd = new SqlCommand();
  1287. bool mustCloseConnection = false;
  1288. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  1289.  
  1290. // Execute the command & return the results
  1291. object retval = cmd.ExecuteScalar();
  1292.  
  1293. // Detach the SqlParameters from the command object, so they can be used again
  1294. cmd.Parameters.Clear();
  1295. return retval;
  1296. }
  1297.  
  1298. /// <summary>
  1299. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified
  1300. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1301. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1302. /// </summary>
  1303. /// <remarks>
  1304. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1305. ///
  1306. /// e.g.:
  1307. /// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
  1308. /// </remarks>
  1309. /// <param name="transaction">A valid SqlTransaction</param>
  1310. /// <param name="spName">The name of the stored procedure</param>
  1311. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1312. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1313. public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
  1314. {
  1315. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1316. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1317. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1318.  
  1319. // If we receive parameter values, we need to figure out where they go
  1320. if ((parameterValues != null) && (parameterValues.Length > ))
  1321. {
  1322. // PPull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1323. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1324.  
  1325. // Assign the provided values to these parameters based on parameter order
  1326. AssignParameterValues(commandParameters, parameterValues);
  1327.  
  1328. // Call the overload that takes an array of SqlParameters
  1329. return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1330. }
  1331. else
  1332. {
  1333. // Otherwise we can just call the SP without params
  1334. return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
  1335. }
  1336. }
  1337.  
  1338. #endregion ExecuteScalar
  1339.  
  1340. #region ExecuteXmlReader
  1341. /// <summary>
  1342. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  1343. /// </summary>
  1344. /// <remarks>
  1345. /// e.g.:
  1346. /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
  1347. /// </remarks>
  1348. /// <param name="connection">A valid SqlConnection</param>
  1349. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1350. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1351. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1352. public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
  1353. {
  1354. // Pass through the call providing null for the set of SqlParameters
  1355. return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
  1356. }
  1357.  
  1358. /// <summary>
  1359. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  1360. /// using the provided parameters.
  1361. /// </summary>
  1362. /// <remarks>
  1363. /// e.g.:
  1364. /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  1365. /// </remarks>
  1366. /// <param name="connection">A valid SqlConnection</param>
  1367. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1368. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1369. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1370. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1371. public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1372. {
  1373. if( connection == null ) throw new ArgumentNullException( "connection" );
  1374.  
  1375. bool mustCloseConnection = false;
  1376. // Create a command and prepare it for execution
  1377. SqlCommand cmd = new SqlCommand();
  1378. try
  1379. {
  1380. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
  1381.  
  1382. // Create the DataAdapter & DataSet
  1383. XmlReader retval = cmd.ExecuteXmlReader();
  1384.  
  1385. // Detach the SqlParameters from the command object, so they can be used again
  1386. cmd.Parameters.Clear();
  1387.  
  1388. return retval;
  1389. }
  1390. catch
  1391. {
  1392. if( mustCloseConnection )
  1393. connection.Close();
  1394. throw;
  1395. }
  1396. }
  1397.  
  1398. /// <summary>
  1399. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  1400. /// using the provided parameter values. This method will query the database to discover the parameters for the
  1401. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1402. /// </summary>
  1403. /// <remarks>
  1404. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1405. ///
  1406. /// e.g.:
  1407. /// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
  1408. /// </remarks>
  1409. /// <param name="connection">A valid SqlConnection</param>
  1410. /// <param name="spName">The name of the stored procedure using "FOR XML AUTO"</param>
  1411. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1412. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1413. public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
  1414. {
  1415. if( connection == null ) throw new ArgumentNullException( "connection" );
  1416. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1417.  
  1418. // If we receive parameter values, we need to figure out where they go
  1419. if ((parameterValues != null) && (parameterValues.Length > ))
  1420. {
  1421. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1422. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1423.  
  1424. // Assign the provided values to these parameters based on parameter order
  1425. AssignParameterValues(commandParameters, parameterValues);
  1426.  
  1427. // Call the overload that takes an array of SqlParameters
  1428. return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  1429. }
  1430. else
  1431. {
  1432. // Otherwise we can just call the SP without params
  1433. return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
  1434. }
  1435. }
  1436.  
  1437. /// <summary>
  1438. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  1439. /// </summary>
  1440. /// <remarks>
  1441. /// e.g.:
  1442. /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
  1443. /// </remarks>
  1444. /// <param name="transaction">A valid SqlTransaction</param>
  1445. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1446. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1447. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1448. public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
  1449. {
  1450. // Pass through the call providing null for the set of SqlParameters
  1451. return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
  1452. }
  1453.  
  1454. /// <summary>
  1455. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  1456. /// using the provided parameters.
  1457. /// </summary>
  1458. /// <remarks>
  1459. /// e.g.:
  1460. /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  1461. /// </remarks>
  1462. /// <param name="transaction">A valid SqlTransaction</param>
  1463. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1464. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1465. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1466. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1467. public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1468. {
  1469. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1470. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1471.  
  1472. // Create a command and prepare it for execution
  1473. SqlCommand cmd = new SqlCommand();
  1474. bool mustCloseConnection = false;
  1475. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  1476.  
  1477. // Create the DataAdapter & DataSet
  1478. XmlReader retval = cmd.ExecuteXmlReader();
  1479.  
  1480. // Detach the SqlParameters from the command object, so they can be used again
  1481. cmd.Parameters.Clear();
  1482. return retval;
  1483. }
  1484.  
  1485. /// <summary>
  1486. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  1487. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1488. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1489. /// </summary>
  1490. /// <remarks>
  1491. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1492. ///
  1493. /// e.g.:
  1494. /// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
  1495. /// </remarks>
  1496. /// <param name="transaction">A valid SqlTransaction</param>
  1497. /// <param name="spName">The name of the stored procedure</param>
  1498. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1499. /// <returns>A dataset containing the resultset generated by the command</returns>
  1500. public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
  1501. {
  1502. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1503. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1504. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1505.  
  1506. // If we receive parameter values, we need to figure out where they go
  1507. if ((parameterValues != null) && (parameterValues.Length > ))
  1508. {
  1509. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1510. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1511.  
  1512. // Assign the provided values to these parameters based on parameter order
  1513. AssignParameterValues(commandParameters, parameterValues);
  1514.  
  1515. // Call the overload that takes an array of SqlParameters
  1516. return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1517. }
  1518. else
  1519. {
  1520. // Otherwise we can just call the SP without params
  1521. return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
  1522. }
  1523. }
  1524.  
  1525. #endregion ExecuteXmlReader
  1526.  
  1527. #region FillDataset
  1528. /// <summary>
  1529. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  1530. /// the connection string.
  1531. /// </summary>
  1532. /// <remarks>
  1533. /// e.g.:
  1534. /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
  1535. /// </remarks>
  1536. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1537. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1538. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1539. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1540. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1541. /// by a user defined name (probably the actual table name)</param>
  1542. public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
  1543. {
  1544. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  1545. if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
  1546.  
  1547. // Create & open a SqlConnection, and dispose of it after we are done
  1548. using (SqlConnection connection = new SqlConnection(connectionString))
  1549. {
  1550. connection.Open();
  1551.  
  1552. // Call the overload that takes a connection in place of the connection string
  1553. FillDataset(connection, commandType, commandText, dataSet, tableNames);
  1554. }
  1555. }
  1556.  
  1557. /// <summary>
  1558. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  1559. /// using the provided parameters.
  1560. /// </summary>
  1561. /// <remarks>
  1562. /// e.g.:
  1563. /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1564. /// </remarks>
  1565. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1566. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1567. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1568. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1569. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1570. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1571. /// by a user defined name (probably the actual table name)
  1572. /// </param>
  1573. public static void FillDataset(string connectionString, CommandType commandType,
  1574. string commandText, DataSet dataSet, string[] tableNames,
  1575. params SqlParameter[] commandParameters)
  1576. {
  1577. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  1578. if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
  1579. // Create & open a SqlConnection, and dispose of it after we are done
  1580. using (SqlConnection connection = new SqlConnection(connectionString))
  1581. {
  1582. connection.Open();
  1583.  
  1584. // Call the overload that takes a connection in place of the connection string
  1585. FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
  1586. }
  1587. }
  1588.  
  1589. /// <summary>
  1590. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  1591. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  1592. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1593. /// </summary>
  1594. /// <remarks>
  1595. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1596. ///
  1597. /// e.g.:
  1598. /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, 24);
  1599. /// </remarks>
  1600. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1601. /// <param name="spName">The name of the stored procedure</param>
  1602. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1603. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1604. /// by a user defined name (probably the actual table name)
  1605. /// </param>
  1606. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1607. public static void FillDataset(string connectionString, string spName,
  1608. DataSet dataSet, string[] tableNames,
  1609. params object[] parameterValues)
  1610. {
  1611. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  1612. if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
  1613. // Create & open a SqlConnection, and dispose of it after we are done
  1614. using (SqlConnection connection = new SqlConnection(connectionString))
  1615. {
  1616. connection.Open();
  1617.  
  1618. // Call the overload that takes a connection in place of the connection string
  1619. FillDataset (connection, spName, dataSet, tableNames, parameterValues);
  1620. }
  1621. }
  1622.  
  1623. /// <summary>
  1624. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  1625. /// </summary>
  1626. /// <remarks>
  1627. /// e.g.:
  1628. /// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
  1629. /// </remarks>
  1630. /// <param name="connection">A valid SqlConnection</param>
  1631. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1632. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1633. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1634. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1635. /// by a user defined name (probably the actual table name)
  1636. /// </param>
  1637. public static void FillDataset(SqlConnection connection, CommandType commandType,
  1638. string commandText, DataSet dataSet, string[] tableNames)
  1639. {
  1640. FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
  1641. }
  1642.  
  1643. /// <summary>
  1644. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  1645. /// using the provided parameters.
  1646. /// </summary>
  1647. /// <remarks>
  1648. /// e.g.:
  1649. /// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1650. /// </remarks>
  1651. /// <param name="connection">A valid SqlConnection</param>
  1652. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1653. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1654. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1655. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1656. /// by a user defined name (probably the actual table name)
  1657. /// </param>
  1658. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1659. public static void FillDataset(SqlConnection connection, CommandType commandType,
  1660. string commandText, DataSet dataSet, string[] tableNames,
  1661. params SqlParameter[] commandParameters)
  1662. {
  1663. FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
  1664. }
  1665.  
  1666. /// <summary>
  1667. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  1668. /// using the provided parameter values. This method will query the database to discover the parameters for the
  1669. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1670. /// </summary>
  1671. /// <remarks>
  1672. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1673. ///
  1674. /// e.g.:
  1675. /// FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, 24, 36);
  1676. /// </remarks>
  1677. /// <param name="connection">A valid SqlConnection</param>
  1678. /// <param name="spName">The name of the stored procedure</param>
  1679. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1680. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1681. /// by a user defined name (probably the actual table name)
  1682. /// </param>
  1683. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1684. public static void FillDataset(SqlConnection connection, string spName,
  1685. DataSet dataSet, string[] tableNames,
  1686. params object[] parameterValues)
  1687. {
  1688. if ( connection == null ) throw new ArgumentNullException( "connection" );
  1689. if (dataSet == null ) throw new ArgumentNullException( "dataSet" );
  1690. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1691.  
  1692. // If we receive parameter values, we need to figure out where they go
  1693. if ((parameterValues != null) && (parameterValues.Length > ))
  1694. {
  1695. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1696. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1697.  
  1698. // Assign the provided values to these parameters based on parameter order
  1699. AssignParameterValues(commandParameters, parameterValues);
  1700.  
  1701. // Call the overload that takes an array of SqlParameters
  1702. FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
  1703. }
  1704. else
  1705. {
  1706. // Otherwise we can just call the SP without params
  1707. FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
  1708. }
  1709. }
  1710.  
  1711. /// <summary>
  1712. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  1713. /// </summary>
  1714. /// <remarks>
  1715. /// e.g.:
  1716. /// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
  1717. /// </remarks>
  1718. /// <param name="transaction">A valid SqlTransaction</param>
  1719. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1720. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1721. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1722. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1723. /// by a user defined name (probably the actual table name)
  1724. /// </param>
  1725. public static void FillDataset(SqlTransaction transaction, CommandType commandType,
  1726. string commandText,
  1727. DataSet dataSet, string[] tableNames)
  1728. {
  1729. FillDataset (transaction, commandType, commandText, dataSet, tableNames, null);
  1730. }
  1731.  
  1732. /// <summary>
  1733. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  1734. /// using the provided parameters.
  1735. /// </summary>
  1736. /// <remarks>
  1737. /// e.g.:
  1738. /// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1739. /// </remarks>
  1740. /// <param name="transaction">A valid SqlTransaction</param>
  1741. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1742. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1743. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1744. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1745. /// by a user defined name (probably the actual table name)
  1746. /// </param>
  1747. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1748. public static void FillDataset(SqlTransaction transaction, CommandType commandType,
  1749. string commandText, DataSet dataSet, string[] tableNames,
  1750. params SqlParameter[] commandParameters)
  1751. {
  1752. FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
  1753. }
  1754.  
  1755. /// <summary>
  1756. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  1757. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1758. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1759. /// </summary>
  1760. /// <remarks>
  1761. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1762. ///
  1763. /// e.g.:
  1764. /// FillDataset(trans, "GetOrders", ds, new string[]{"orders"}, 24, 36);
  1765. /// </remarks>
  1766. /// <param name="transaction">A valid SqlTransaction</param>
  1767. /// <param name="spName">The name of the stored procedure</param>
  1768. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1769. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1770. /// by a user defined name (probably the actual table name)
  1771. /// </param>
  1772. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1773. public static void FillDataset(SqlTransaction transaction, string spName,
  1774. DataSet dataSet, string[] tableNames,
  1775. params object[] parameterValues)
  1776. {
  1777. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  1778. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  1779. if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
  1780. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1781.  
  1782. // If we receive parameter values, we need to figure out where they go
  1783. if ((parameterValues != null) && (parameterValues.Length > ))
  1784. {
  1785. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1786. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1787.  
  1788. // Assign the provided values to these parameters based on parameter order
  1789. AssignParameterValues(commandParameters, parameterValues);
  1790.  
  1791. // Call the overload that takes an array of SqlParameters
  1792. FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
  1793. }
  1794. else
  1795. {
  1796. // Otherwise we can just call the SP without params
  1797. FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
  1798. }
  1799. }
  1800.  
  1801. /// <summary>
  1802. /// Private helper method that execute a SqlCommand (that returns a resultset) against the specified SqlTransaction and SqlConnection
  1803. /// using the provided parameters.
  1804. /// </summary>
  1805. /// <remarks>
  1806. /// e.g.:
  1807. /// FillDataset(conn, trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1808. /// </remarks>
  1809. /// <param name="connection">A valid SqlConnection</param>
  1810. /// <param name="transaction">A valid SqlTransaction</param>
  1811. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1812. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1813. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1814. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1815. /// by a user defined name (probably the actual table name)
  1816. /// </param>
  1817. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1818. private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType,
  1819. string commandText, DataSet dataSet, string[] tableNames,
  1820. params SqlParameter[] commandParameters)
  1821. {
  1822. if( connection == null ) throw new ArgumentNullException( "connection" );
  1823. if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
  1824.  
  1825. // Create a command and prepare it for execution
  1826. SqlCommand command = new SqlCommand();
  1827. bool mustCloseConnection = false;
  1828. PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
  1829.  
  1830. // Create the DataAdapter & DataSet
  1831. using( SqlDataAdapter dataAdapter = new SqlDataAdapter(command) )
  1832. {
  1833.  
  1834. // Add the table mappings specified by the user
  1835. if (tableNames != null && tableNames.Length > )
  1836. {
  1837. string tableName = "Table";
  1838. for (int index=; index < tableNames.Length; index++)
  1839. {
  1840. if( tableNames[index] == null || tableNames[index].Length == ) throw new ArgumentException( "The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames" );
  1841. dataAdapter.TableMappings.Add(tableName, tableNames[index]);
  1842. tableName += (index + ).ToString();
  1843. }
  1844. }
  1845.  
  1846. // Fill the DataSet using default values for DataTable names, etc
  1847. dataAdapter.Fill(dataSet);
  1848.  
  1849. // Detach the SqlParameters from the command object, so they can be used again
  1850. command.Parameters.Clear();
  1851. }
  1852.  
  1853. if( mustCloseConnection )
  1854. connection.Close();
  1855. }
  1856. #endregion
  1857.  
  1858. #region UpdateDataset
  1859. /// <summary>
  1860. /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
  1861. /// </summary>
  1862. /// <remarks>
  1863. /// e.g.:
  1864. /// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
  1865. /// </remarks>
  1866. /// <param name="insertCommand">A valid transact-SQL statement or stored procedure to insert new records into the data source</param>
  1867. /// <param name="deleteCommand">A valid transact-SQL statement or stored procedure to delete records from the data source</param>
  1868. /// <param name="updateCommand">A valid transact-SQL statement or stored procedure used to update records in the data source</param>
  1869. /// <param name="dataSet">The DataSet used to update the data source</param>
  1870. /// <param name="tableName">The DataTable used to update the data source.</param>
  1871. public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
  1872. {
  1873. if( insertCommand == null ) throw new ArgumentNullException( "insertCommand" );
  1874. if( deleteCommand == null ) throw new ArgumentNullException( "deleteCommand" );
  1875. if( updateCommand == null ) throw new ArgumentNullException( "updateCommand" );
  1876. if( tableName == null || tableName.Length == ) throw new ArgumentNullException( "tableName" );
  1877.  
  1878. // Create a SqlDataAdapter, and dispose of it after we are done
  1879. using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
  1880. {
  1881. // Set the data adapter commands
  1882. dataAdapter.UpdateCommand = updateCommand;
  1883. dataAdapter.InsertCommand = insertCommand;
  1884. dataAdapter.DeleteCommand = deleteCommand;
  1885.  
  1886. // Update the dataset changes in the data source
  1887. dataAdapter.Update (dataSet, tableName);
  1888.  
  1889. // Commit all the changes made to the DataSet
  1890. dataSet.AcceptChanges();
  1891. }
  1892. }
  1893. #endregion
  1894.  
  1895. #region CreateCommand
  1896. /// <summary>
  1897. /// Simplify the creation of a Sql command object by allowing
  1898. /// a stored procedure and optional parameters to be provided
  1899. /// </summary>
  1900. /// <remarks>
  1901. /// e.g.:
  1902. /// SqlCommand command = CreateCommand(conn, "AddCustomer", "CustomerID", "CustomerName");
  1903. /// </remarks>
  1904. /// <param name="connection">A valid SqlConnection object</param>
  1905. /// <param name="spName">The name of the stored procedure</param>
  1906. /// <param name="sourceColumns">An array of string to be assigned as the source columns of the stored procedure parameters</param>
  1907. /// <returns>A valid SqlCommand object</returns>
  1908. public static SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns)
  1909. {
  1910. if( connection == null ) throw new ArgumentNullException( "connection" );
  1911. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1912.  
  1913. // Create a SqlCommand
  1914. SqlCommand cmd = new SqlCommand( spName, connection );
  1915. cmd.CommandType = CommandType.StoredProcedure;
  1916.  
  1917. // If we receive parameter values, we need to figure out where they go
  1918. if ((sourceColumns != null) && (sourceColumns.Length > ))
  1919. {
  1920. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1921. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1922.  
  1923. // Assign the provided source columns to these parameters based on parameter order
  1924. for (int index=; index < sourceColumns.Length; index++)
  1925. commandParameters[index].SourceColumn = sourceColumns[index];
  1926.  
  1927. // Attach the discovered parameters to the SqlCommand object
  1928. AttachParameters (cmd, commandParameters);
  1929. }
  1930.  
  1931. return cmd;
  1932. }
  1933. #endregion
  1934.  
  1935. #region ExecuteNonQueryTypedParams
  1936. /// <summary>
  1937. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
  1938. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  1939. /// This method will query the database to discover the parameters for the
  1940. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  1941. /// </summary>
  1942. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1943. /// <param name="spName">The name of the stored procedure</param>
  1944. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  1945. /// <returns>An int representing the number of rows affected by the command</returns>
  1946. public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow)
  1947. {
  1948. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  1949. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1950.  
  1951. // If the row has values, the store procedure parameters must be initialized
  1952. if (dataRow != null && dataRow.ItemArray.Length > )
  1953. {
  1954. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1955. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  1956.  
  1957. // Set the parameters values
  1958. AssignParameterValues(commandParameters, dataRow);
  1959.  
  1960. return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  1961. }
  1962. else
  1963. {
  1964. return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
  1965. }
  1966. }
  1967.  
  1968. /// <summary>
  1969. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
  1970. /// using the dataRow column values as the stored procedure's parameters values.
  1971. /// This method will query the database to discover the parameters for the
  1972. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  1973. /// </summary>
  1974. /// <param name="connection">A valid SqlConnection object</param>
  1975. /// <param name="spName">The name of the stored procedure</param>
  1976. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  1977. /// <returns>An int representing the number of rows affected by the command</returns>
  1978. public static int ExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  1979. {
  1980. if( connection == null ) throw new ArgumentNullException( "connection" );
  1981. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  1982.  
  1983. // If the row has values, the store procedure parameters must be initialized
  1984. if (dataRow != null && dataRow.ItemArray.Length > )
  1985. {
  1986. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1987. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1988.  
  1989. // Set the parameters values
  1990. AssignParameterValues(commandParameters, dataRow);
  1991.  
  1992. return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  1993. }
  1994. else
  1995. {
  1996. return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
  1997. }
  1998. }
  1999.  
  2000. /// <summary>
  2001. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
  2002. /// SqlTransaction using the dataRow column values as the stored procedure's parameters values.
  2003. /// This method will query the database to discover the parameters for the
  2004. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2005. /// </summary>
  2006. /// <param name="transaction">A valid SqlTransaction object</param>
  2007. /// <param name="spName">The name of the stored procedure</param>
  2008. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2009. /// <returns>An int representing the number of rows affected by the command</returns>
  2010. public static int ExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2011. {
  2012. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  2013. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  2014. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2015.  
  2016. // Sf the row has values, the store procedure parameters must be initialized
  2017. if (dataRow != null && dataRow.ItemArray.Length > )
  2018. {
  2019. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2020. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2021.  
  2022. // Set the parameters values
  2023. AssignParameterValues(commandParameters, dataRow);
  2024.  
  2025. return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2026. }
  2027. else
  2028. {
  2029. return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
  2030. }
  2031. }
  2032. #endregion
  2033.  
  2034. #region ExecuteDatasetTypedParams
  2035. /// <summary>
  2036. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  2037. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  2038. /// This method will query the database to discover the parameters for the
  2039. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2040. /// </summary>
  2041. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2042. /// <param name="spName">The name of the stored procedure</param>
  2043. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2044. /// <returns>A dataset containing the resultset generated by the command</returns>
  2045. public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow)
  2046. {
  2047. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  2048. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2049.  
  2050. //If the row has values, the store procedure parameters must be initialized
  2051. if ( dataRow != null && dataRow.ItemArray.Length > )
  2052. {
  2053. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2054. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  2055.  
  2056. // Set the parameters values
  2057. AssignParameterValues(commandParameters, dataRow);
  2058.  
  2059. return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  2060. }
  2061. else
  2062. {
  2063. return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  2064. }
  2065. }
  2066.  
  2067. /// <summary>
  2068. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  2069. /// using the dataRow column values as the store procedure's parameters values.
  2070. /// This method will query the database to discover the parameters for the
  2071. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2072. /// </summary>
  2073. /// <param name="connection">A valid SqlConnection object</param>
  2074. /// <param name="spName">The name of the stored procedure</param>
  2075. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2076. /// <returns>A dataset containing the resultset generated by the command</returns>
  2077. public static DataSet ExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2078. {
  2079. if( connection == null ) throw new ArgumentNullException( "connection" );
  2080. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2081.  
  2082. // If the row has values, the store procedure parameters must be initialized
  2083. if( dataRow != null && dataRow.ItemArray.Length > )
  2084. {
  2085. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2086. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2087.  
  2088. // Set the parameters values
  2089. AssignParameterValues(commandParameters, dataRow);
  2090.  
  2091. return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  2092. }
  2093. else
  2094. {
  2095. return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
  2096. }
  2097. }
  2098.  
  2099. /// <summary>
  2100. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
  2101. /// using the dataRow column values as the stored procedure's parameters values.
  2102. /// This method will query the database to discover the parameters for the
  2103. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2104. /// </summary>
  2105. /// <param name="transaction">A valid SqlTransaction object</param>
  2106. /// <param name="spName">The name of the stored procedure</param>
  2107. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2108. /// <returns>A dataset containing the resultset generated by the command</returns>
  2109. public static DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2110. {
  2111. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  2112. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  2113. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2114.  
  2115. // If the row has values, the store procedure parameters must be initialized
  2116. if( dataRow != null && dataRow.ItemArray.Length > )
  2117. {
  2118. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2119. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2120.  
  2121. // Set the parameters values
  2122. AssignParameterValues(commandParameters, dataRow);
  2123.  
  2124. return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2125. }
  2126. else
  2127. {
  2128. return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
  2129. }
  2130. }
  2131.  
  2132. #endregion
  2133.  
  2134. #region ExecuteReaderTypedParams
  2135. /// <summary>
  2136. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  2137. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  2138. /// This method will query the database to discover the parameters for the
  2139. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2140. /// </summary>
  2141. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2142. /// <param name="spName">The name of the stored procedure</param>
  2143. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2144. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  2145. public static SqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow)
  2146. {
  2147. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  2148. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2149.  
  2150. // If the row has values, the store procedure parameters must be initialized
  2151. if ( dataRow != null && dataRow.ItemArray.Length > )
  2152. {
  2153. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2154. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  2155.  
  2156. // Set the parameters values
  2157. AssignParameterValues(commandParameters, dataRow);
  2158.  
  2159. return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  2160. }
  2161. else
  2162. {
  2163. return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
  2164. }
  2165. }
  2166.  
  2167. /// <summary>
  2168. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  2169. /// using the dataRow column values as the stored procedure's parameters values.
  2170. /// This method will query the database to discover the parameters for the
  2171. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2172. /// </summary>
  2173. /// <param name="connection">A valid SqlConnection object</param>
  2174. /// <param name="spName">The name of the stored procedure</param>
  2175. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2176. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  2177. public static SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2178. {
  2179. if( connection == null ) throw new ArgumentNullException( "connection" );
  2180. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2181.  
  2182. // If the row has values, the store procedure parameters must be initialized
  2183. if( dataRow != null && dataRow.ItemArray.Length > )
  2184. {
  2185. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2186. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2187.  
  2188. // Set the parameters values
  2189. AssignParameterValues(commandParameters, dataRow);
  2190.  
  2191. return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  2192. }
  2193. else
  2194. {
  2195. return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
  2196. }
  2197. }
  2198.  
  2199. /// <summary>
  2200. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
  2201. /// using the dataRow column values as the stored procedure's parameters values.
  2202. /// This method will query the database to discover the parameters for the
  2203. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2204. /// </summary>
  2205. /// <param name="transaction">A valid SqlTransaction object</param>
  2206. /// <param name="spName">The name of the stored procedure</param>
  2207. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2208. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  2209. public static SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2210. {
  2211. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  2212. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  2213. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2214.  
  2215. // If the row has values, the store procedure parameters must be initialized
  2216. if( dataRow != null && dataRow.ItemArray.Length > )
  2217. {
  2218. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2219. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2220.  
  2221. // Set the parameters values
  2222. AssignParameterValues(commandParameters, dataRow);
  2223.  
  2224. return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2225. }
  2226. else
  2227. {
  2228. return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
  2229. }
  2230. }
  2231. #endregion
  2232.  
  2233. #region ExecuteScalarTypedParams
  2234. /// <summary>
  2235. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
  2236. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  2237. /// This method will query the database to discover the parameters for the
  2238. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2239. /// </summary>
  2240. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2241. /// <param name="spName">The name of the stored procedure</param>
  2242. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2243. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  2244. public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow)
  2245. {
  2246. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  2247. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2248.  
  2249. // If the row has values, the store procedure parameters must be initialized
  2250. if( dataRow != null && dataRow.ItemArray.Length > )
  2251. {
  2252. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2253. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  2254.  
  2255. // Set the parameters values
  2256. AssignParameterValues(commandParameters, dataRow);
  2257.  
  2258. return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  2259. }
  2260. else
  2261. {
  2262. return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
  2263. }
  2264. }
  2265.  
  2266. /// <summary>
  2267. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
  2268. /// using the dataRow column values as the stored procedure's parameters values.
  2269. /// This method will query the database to discover the parameters for the
  2270. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2271. /// </summary>
  2272. /// <param name="connection">A valid SqlConnection object</param>
  2273. /// <param name="spName">The name of the stored procedure</param>
  2274. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2275. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  2276. public static object ExecuteScalarTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2277. {
  2278. if( connection == null ) throw new ArgumentNullException( "connection" );
  2279. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2280.  
  2281. // If the row has values, the store procedure parameters must be initialized
  2282. if( dataRow != null && dataRow.ItemArray.Length > )
  2283. {
  2284. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2285. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2286.  
  2287. // Set the parameters values
  2288. AssignParameterValues(commandParameters, dataRow);
  2289.  
  2290. return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
  2291. }
  2292. else
  2293. {
  2294. return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
  2295. }
  2296. }
  2297.  
  2298. /// <summary>
  2299. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
  2300. /// using the dataRow column values as the stored procedure's parameters values.
  2301. /// This method will query the database to discover the parameters for the
  2302. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2303. /// </summary>
  2304. /// <param name="transaction">A valid SqlTransaction object</param>
  2305. /// <param name="spName">The name of the stored procedure</param>
  2306. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2307. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  2308. public static object ExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2309. {
  2310. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  2311. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  2312. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2313.  
  2314. // If the row has values, the store procedure parameters must be initialized
  2315. if( dataRow != null && dataRow.ItemArray.Length > )
  2316. {
  2317. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2318. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2319.  
  2320. // Set the parameters values
  2321. AssignParameterValues(commandParameters, dataRow);
  2322.  
  2323. return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2324. }
  2325. else
  2326. {
  2327. return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
  2328. }
  2329. }
  2330. #endregion
  2331.  
  2332. #region ExecuteXmlReaderTypedParams
  2333. /// <summary>
  2334. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  2335. /// using the dataRow column values as the stored procedure's parameters values.
  2336. /// This method will query the database to discover the parameters for the
  2337. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2338. /// </summary>
  2339. /// <param name="connection">A valid SqlConnection object</param>
  2340. /// <param name="spName">The name of the stored procedure</param>
  2341. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2342. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  2343. public static XmlReader ExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2344. {
  2345. if( connection == null ) throw new ArgumentNullException( "connection" );
  2346. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2347.  
  2348. // If the row has values, the store procedure parameters must be initialized
  2349. if( dataRow != null && dataRow.ItemArray.Length > )
  2350. {
  2351. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2352. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2353.  
  2354. // Set the parameters values
  2355. AssignParameterValues(commandParameters, dataRow);
  2356.  
  2357. return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  2358. }
  2359. else
  2360. {
  2361. return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
  2362. }
  2363. }
  2364.  
  2365. /// <summary>
  2366. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
  2367. /// using the dataRow column values as the stored procedure's parameters values.
  2368. /// This method will query the database to discover the parameters for the
  2369. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2370. /// </summary>
  2371. /// <param name="transaction">A valid SqlTransaction object</param>
  2372. /// <param name="spName">The name of the stored procedure</param>
  2373. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2374. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  2375. public static XmlReader ExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2376. {
  2377. if( transaction == null ) throw new ArgumentNullException( "transaction" );
  2378. if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
  2379. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2380.  
  2381. // If the row has values, the store procedure parameters must be initialized
  2382. if( dataRow != null && dataRow.ItemArray.Length > )
  2383. {
  2384. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2385. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2386.  
  2387. // Set the parameters values
  2388. AssignParameterValues(commandParameters, dataRow);
  2389.  
  2390. return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2391. }
  2392. else
  2393. {
  2394. return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
  2395. }
  2396. }
  2397. #endregion
  2398.  
  2399. }
  2400.  
  2401. /// <summary>
  2402. /// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
  2403. /// ability to discover parameters for stored procedures at run-time.
  2404. /// </summary>
  2405. public sealed class SqlHelperParameterCache
  2406. {
  2407. #region private methods, variables, and constructors
  2408.  
  2409. //Since this class provides only static methods, make the default constructor private to prevent
  2410. //instances from being created with "new SqlHelperParameterCache()"
  2411. private SqlHelperParameterCache() {}
  2412.  
  2413. private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
  2414.  
  2415. /// <summary>
  2416. /// Resolve at run time the appropriate set of SqlParameters for a stored procedure
  2417. /// </summary>
  2418. /// <param name="connection">A valid SqlConnection object</param>
  2419. /// <param name="spName">The name of the stored procedure</param>
  2420. /// <param name="includeReturnValueParameter">Whether or not to include their return value parameter</param>
  2421. /// <returns>The parameter array discovered.</returns>
  2422. private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
  2423. {
  2424. if( connection == null ) throw new ArgumentNullException( "connection" );
  2425. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2426.  
  2427. SqlCommand cmd = new SqlCommand(spName, connection);
  2428. cmd.CommandType = CommandType.StoredProcedure;
  2429.  
  2430. connection.Open();
  2431. SqlCommandBuilder.DeriveParameters(cmd);
  2432. connection.Close();
  2433.  
  2434. if (!includeReturnValueParameter)
  2435. {
  2436. cmd.Parameters.RemoveAt();
  2437. }
  2438.  
  2439. SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];
  2440.  
  2441. cmd.Parameters.CopyTo(discoveredParameters, );
  2442.  
  2443. // Init the parameters with a DBNull value
  2444. foreach (SqlParameter discoveredParameter in discoveredParameters)
  2445. {
  2446. discoveredParameter.Value = DBNull.Value;
  2447. }
  2448. return discoveredParameters;
  2449. }
  2450.  
  2451. /// <summary>
  2452. /// Deep copy of cached SqlParameter array
  2453. /// </summary>
  2454. /// <param name="originalParameters"></param>
  2455. /// <returns></returns>
  2456. private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
  2457. {
  2458. SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];
  2459.  
  2460. for (int i = , j = originalParameters.Length; i < j; i++)
  2461. {
  2462. clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
  2463. }
  2464.  
  2465. return clonedParameters;
  2466. }
  2467.  
  2468. #endregion private methods, variables, and constructors
  2469.  
  2470. #region caching functions
  2471.  
  2472. /// <summary>
  2473. /// Add parameter array to the cache
  2474. /// </summary>
  2475. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2476. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  2477. /// <param name="commandParameters">An array of SqlParamters to be cached</param>
  2478. public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
  2479. {
  2480. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  2481. if( commandText == null || commandText.Length == ) throw new ArgumentNullException( "commandText" );
  2482.  
  2483. string hashKey = connectionString + ":" + commandText;
  2484.  
  2485. paramCache[hashKey] = commandParameters;
  2486. }
  2487.  
  2488. /// <summary>
  2489. /// Retrieve a parameter array from the cache
  2490. /// </summary>
  2491. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2492. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  2493. /// <returns>An array of SqlParamters</returns>
  2494. public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
  2495. {
  2496. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  2497. if( commandText == null || commandText.Length == ) throw new ArgumentNullException( "commandText" );
  2498.  
  2499. string hashKey = connectionString + ":" + commandText;
  2500.  
  2501. SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
  2502. if (cachedParameters == null)
  2503. {
  2504. return null;
  2505. }
  2506. else
  2507. {
  2508. return CloneParameters(cachedParameters);
  2509. }
  2510. }
  2511.  
  2512. #endregion caching functions
  2513.  
  2514. #region Parameter Discovery Functions
  2515.  
  2516. /// <summary>
  2517. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2518. /// </summary>
  2519. /// <remarks>
  2520. /// This method will query the database for this information, and then store it in a cache for future requests.
  2521. /// </remarks>
  2522. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2523. /// <param name="spName">The name of the stored procedure</param>
  2524. /// <returns>An array of SqlParameters</returns>
  2525. public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
  2526. {
  2527. return GetSpParameterSet(connectionString, spName, false);
  2528. }
  2529.  
  2530. /// <summary>
  2531. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2532. /// </summary>
  2533. /// <remarks>
  2534. /// This method will query the database for this information, and then store it in a cache for future requests.
  2535. /// </remarks>
  2536. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2537. /// <param name="spName">The name of the stored procedure</param>
  2538. /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
  2539. /// <returns>An array of SqlParameters</returns>
  2540. public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
  2541. {
  2542. if( connectionString == null || connectionString.Length == ) throw new ArgumentNullException( "connectionString" );
  2543. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2544.  
  2545. using(SqlConnection connection = new SqlConnection(connectionString))
  2546. {
  2547. return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
  2548. }
  2549. }
  2550.  
  2551. /// <summary>
  2552. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2553. /// </summary>
  2554. /// <remarks>
  2555. /// This method will query the database for this information, and then store it in a cache for future requests.
  2556. /// </remarks>
  2557. /// <param name="connection">A valid SqlConnection object</param>
  2558. /// <param name="spName">The name of the stored procedure</param>
  2559. /// <returns>An array of SqlParameters</returns>
  2560. internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
  2561. {
  2562. return GetSpParameterSet(connection, spName, false);
  2563. }
  2564.  
  2565. /// <summary>
  2566. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2567. /// </summary>
  2568. /// <remarks>
  2569. /// This method will query the database for this information, and then store it in a cache for future requests.
  2570. /// </remarks>
  2571. /// <param name="connection">A valid SqlConnection object</param>
  2572. /// <param name="spName">The name of the stored procedure</param>
  2573. /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
  2574. /// <returns>An array of SqlParameters</returns>
  2575. internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
  2576. {
  2577. if( connection == null ) throw new ArgumentNullException( "connection" );
  2578. using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone())
  2579. {
  2580. return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
  2581. }
  2582. }
  2583.  
  2584. /// <summary>
  2585. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2586. /// </summary>
  2587. /// <param name="connection">A valid SqlConnection object</param>
  2588. /// <param name="spName">The name of the stored procedure</param>
  2589. /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
  2590. /// <returns>An array of SqlParameters</returns>
  2591. private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter)
  2592. {
  2593. if( connection == null ) throw new ArgumentNullException( "connection" );
  2594. if( spName == null || spName.Length == ) throw new ArgumentNullException( "spName" );
  2595.  
  2596. string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter":"");
  2597.  
  2598. SqlParameter[] cachedParameters;
  2599.  
  2600. cachedParameters = paramCache[hashKey] as SqlParameter[];
  2601. if (cachedParameters == null)
  2602. {
  2603. SqlParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
  2604. paramCache[hashKey] = spParameters;
  2605. cachedParameters = spParameters;
  2606. }
  2607.  
  2608. return CloneParameters(cachedParameters);
  2609. }
  2610.  
  2611. #endregion Parameter Discovery Functions
  2612.  
  2613. }
  2614. }

微软原版SQLHelper类的更多相关文章

  1. 微软官方SqlHelper类 数据库辅助操作类

    数据库操作类真的没有必要自己去写,因为成熟的类库真的非常完善了,拿来直接用就好,省时省力. 本文就为大家介绍微软官方的程序PetShop4.0中的SqlHelper类,先来做一下简单的介绍,PetSh ...

  2. 微软的SQLHelper类(含完整中文注释)

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  3. 【转载】微软官方提供的Sqlserver数据库操作帮助类SQLHelper类

    在.NET平台中,C#语言一般使用ADO.NET组件来操作Sqlserver数据库,通过ADO.NET组件可以实现连接数据库.查询数据集.执行SQL语句以及关闭数据库连接等操作,为此网上有很多开发者自 ...

  4. 最新的SqlHelper 类

    最新的SqlHelper 类 摘自:http://www.cnblogs.com/sufei/archive/2010/01/14/1648026.html using System; using S ...

  5. c#中sqlhelper类的编写(二)

    上一篇文章讲了简易版的SqlHelper类的编写,我们在这里就上一篇文章末尾提出的问题写出解决方案. sql语句注入攻击已经是众所周知的了.我们如何在C#中保护自己的数据库不被这样的方式攻击呢? 不用 ...

  6. JAVA WEB SQLHelper类的封装

    在这次做项目中,我对自己最满意的就是封装了一下SQLHelper类,我对自己感到骄傲主要是 我是初学者,我刚开始不知道可以这样做,我只是想着试着去这样做了,结果真的可以,所以我 在我的模块就自己封装了 ...

  7. c#中sqlhelper类的编写(一)

    在.net平台的项目开发中,凡是用到数据库交互的,都有必要了解SqlHelper类的原理. 步骤一: 我就拿WPF项目开发作为例子.首先要新建一个App.config(应用程序配置文件).注意,在VS ...

  8. [置顶] 自己写sqlhelper类

    自己写sqlhelper类 using System; using System.Collections.Generic; using System.Configuration; using Syst ...

  9. ADO.NET复习——自己编写SqlHelper类

    今天复习了一次ADO.NET基础,整理一下自己的认为的重点: 编写SqlHelper类,方便我们执行数据库语句,这时可以直接调用封装在SqlHelper类的方法.现在大多数公司面试的时候,给你的面试题 ...

随机推荐

  1. Xcode 5.1 更新后插件不能用

    打开目录 ~/Library/Application Support/Developer/Shared/Xcode/Plug-ins 右击选择"显示包内容" 找到"Inf ...

  2. 模板:优先队列(priority_queue)

    #include <iostream> #include <cstdio> #include <queue> #include <vector> usi ...

  3. nginx 代理 proxy_pass设置

    #img.test.com/img1 实际访问的路径是 http://127.0.0.1:123/a1 #img.test.com/img2 实际访问的路径是 http://127.0.0.1:123 ...

  4. sqlserver字符串转日期

    declare   @str   varchar(15)     declare   @dt   datetime     select   @str='2005-8-26'     set   @d ...

  5. mvc中的OutputCache

    mvc4中有一个标记属性OutputCache,用来对ActionResult结果进行缓存,如何理解呢?概括地说,就是当你的请求参数没有发生变化时,直接从缓存中取结果,不会再走服务端的Action代码 ...

  6. Activity的测量(Measure)、布局(Layout)和绘制(Draw)过程分析

    一个Android应用程序窗口里面包含了很多UI元素,这些UI元素是以树形结构来组织的,即它们存在着父子关系,其中,子UI元素位于父UI元素里面,因此,在绘制一个Android应用程序窗口的UI之前, ...

  7. jbpm4.4 spring整合

    jBPM-4.4与Spring集成配置比较容易,这里我使用的是Spring-2.5.6,数据库连接池使用C3P0,将相关的两个jar文件加入到CLASSPATH中. jBPM-4.4与Spring集成 ...

  8. 缓存 Cache

    Controllers层 public class HomeController : Controller    {        //        // GET: /Home/       // ...

  9. 安装Oracle 11gR2,报错:[INS-06101] IP address of localhost could not be determined

    安装Oracle 11gR2,报错:[INS-06101] IP address of localhost could not be determined 出现这种错误是因为主机名和/etc/host ...

  10. Java笔记2 : 泛型的体现,及其上限、下限、通配符

    Java中的泛型是在jdk5.0引入的,语法不难,但是需要注意的细节有很多,这里写一下备忘. 首先是最简单的泛型类,泛型方法,泛型接口: //泛型接口的定义 interface MyInter< ...