PageRenderTime 28ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/Crab.DataModel/Utility/SqlHelper.cs

#
C# | 2811 lines | 1164 code | 314 blank | 1333 comment | 578 complexity | 8ba69f7e429327802591626d3ac5b2ae MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. // ===============================================================================
  2. // Microsoft Data Access Application Block for .NET
  3. // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
  4. //
  5. // SQLHelper.cs
  6. //
  7. // This file contains the implementations of the SqlHelper and SqlHelperParameterCache
  8. // classes.
  9. //
  10. // For more information see the Data Access Application Block Implementation Overview.
  11. // ===============================================================================
  12. // Release history
  13. // VERSION DESCRIPTION
  14. // 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods
  15. //
  16. // ===============================================================================
  17. // Copyright (C) 2000-2001 Microsoft Corporation
  18. // All rights reserved.
  19. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
  20. // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
  21. // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
  22. // FITNESS FOR A PARTICULAR PURPOSE.
  23. // ==============================================================================
  24. using System;
  25. using System.Data;
  26. using System.Xml;
  27. using System.Data.SqlClient;
  28. using System.Collections;
  29. using System.IO;
  30. using System.Configuration;
  31. namespace Crab.DataModel.Utility
  32. {
  33. /// <summary>
  34. /// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
  35. /// common uses of SqlClient
  36. /// </summary>
  37. public sealed class SqlHelper
  38. {
  39. #region private utility methods & constructors
  40. // Since this class provides only static methods, make the default constructor private to prevent
  41. // instances from being created with "new SqlHelper()"
  42. private SqlHelper() { }
  43. /// <summary>
  44. /// This method is used to attach array of SqlParameters to a SqlCommand.
  45. ///
  46. /// This method will assign a value of DbNull to any parameter with a direction of
  47. /// InputOutput and a value of null.
  48. ///
  49. /// This behavior will prevent default values from being used, but
  50. /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
  51. /// where the user provided no input value.
  52. /// </summary>
  53. /// <param name="command">The command to which the parameters will be added</param>
  54. /// <param name="commandParameters">An array of SqlParameters to be added to command</param>
  55. private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
  56. {
  57. if (command == null) throw new ArgumentNullException("command");
  58. if (commandParameters != null)
  59. {
  60. foreach (SqlParameter p in commandParameters)
  61. {
  62. if (p != null)
  63. {
  64. // Check for derived output value with no value assigned
  65. if ((p.Direction == ParameterDirection.InputOutput ||
  66. p.Direction == ParameterDirection.Input) &&
  67. (p.Value == null))
  68. {
  69. p.Value = DBNull.Value;
  70. }
  71. command.Parameters.Add(p);
  72. }
  73. }
  74. }
  75. }
  76. /// <summary>
  77. /// This method assigns dataRow column values to an array of SqlParameters
  78. /// </summary>
  79. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  80. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
  81. private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
  82. {
  83. if ((commandParameters == null) || (dataRow == null))
  84. {
  85. // Do nothing if we get no data
  86. return;
  87. }
  88. int i = 0;
  89. // Set the parameters values
  90. foreach (SqlParameter commandParameter in commandParameters)
  91. {
  92. // Check the parameter name
  93. if (commandParameter.ParameterName == null ||
  94. commandParameter.ParameterName.Length <= 1)
  95. throw new Exception(
  96. string.Format(
  97. "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
  98. i, commandParameter.ParameterName));
  99. if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
  100. commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
  101. i++;
  102. }
  103. }
  104. /// <summary>
  105. /// This method assigns an array of values to an array of SqlParameters
  106. /// </summary>
  107. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  108. /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
  109. private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
  110. {
  111. if ((commandParameters == null) || (parameterValues == null))
  112. {
  113. // Do nothing if we get no data
  114. return;
  115. }
  116. // We must have the same number of values as we pave parameters to put them in
  117. if (commandParameters.Length != parameterValues.Length)
  118. {
  119. throw new ArgumentException("Parameter count does not match Parameter Value count.");
  120. }
  121. // Iterate through the SqlParameters, assigning the values from the corresponding position in the
  122. // value array
  123. for (int i = 0, j = commandParameters.Length; i < j; i++)
  124. {
  125. // If the current array value derives from IDbDataParameter, then assign its Value property
  126. if (parameterValues[i] is IDbDataParameter)
  127. {
  128. IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
  129. if (paramInstance.Value == null)
  130. {
  131. commandParameters[i].Value = DBNull.Value;
  132. }
  133. else
  134. {
  135. commandParameters[i].Value = paramInstance.Value;
  136. }
  137. }
  138. else if (parameterValues[i] == null)
  139. {
  140. commandParameters[i].Value = DBNull.Value;
  141. }
  142. else
  143. {
  144. commandParameters[i].Value = parameterValues[i];
  145. }
  146. }
  147. }
  148. /// <summary>
  149. /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
  150. /// to the provided command
  151. /// </summary>
  152. /// <param name="command">The SqlCommand to be prepared</param>
  153. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  154. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  155. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  156. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  157. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  158. /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
  159. private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
  160. {
  161. if (command == null) throw new ArgumentNullException("command");
  162. if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
  163. // If the provided connection is not open, we will open it
  164. if (connection.State != ConnectionState.Open)
  165. {
  166. mustCloseConnection = true;
  167. connection.Open();
  168. }
  169. else
  170. {
  171. mustCloseConnection = false;
  172. }
  173. // Associate the connection with the command
  174. command.Connection = connection;
  175. // Set the command text (stored procedure name or SQL statement)
  176. command.CommandText = commandText;
  177. // If we were provided a transaction, assign it
  178. if (transaction != null)
  179. {
  180. if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  181. command.Transaction = transaction;
  182. }
  183. // Set the command type
  184. command.CommandType = commandType;
  185. // Attach the command parameters if they are provided
  186. if (commandParameters != null)
  187. {
  188. AttachParameters(command, commandParameters);
  189. }
  190. return;
  191. }
  192. #endregion private utility methods & constructors
  193. #region ExecuteNonQuery
  194. /// <summary>
  195. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
  196. /// the connection string
  197. /// </summary>
  198. /// <remarks>
  199. /// e.g.:
  200. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
  201. /// </remarks>
  202. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  203. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  204. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  205. /// <returns>An int representing the number of rows affected by the command</returns>
  206. public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
  207. {
  208. // Pass through the call providing null for the set of SqlParameters
  209. return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
  210. }
  211. /// <summary>
  212. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  213. /// using the provided parameters
  214. /// </summary>
  215. /// <remarks>
  216. /// e.g.:
  217. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  218. /// </remarks>
  219. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  220. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  221. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  222. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  223. /// <returns>An int representing the number of rows affected by the command</returns>
  224. public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  225. {
  226. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  227. // Create & open a SqlConnection, and dispose of it after we are done
  228. using (SqlConnection connection = new SqlConnection(connectionString))
  229. {
  230. connection.Open();
  231. // Call the overload that takes a connection in place of the connection string
  232. return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
  233. }
  234. }
  235. /// <summary>
  236. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  237. /// using the provided parameters
  238. /// </summary>
  239. /// <remarks>
  240. /// e.g.:
  241. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  242. /// </remarks>
  243. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  244. /// <param name="spName">The stored procedure name</param>
  245. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  246. /// <returns>An int representing the number of rows affected by the command</returns>
  247. public static int ExecuteNonQuery(string connectionString, string spName, params SqlParameter[] commandParameters)
  248. {
  249. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  250. // Create & open a SqlConnection, and dispose of it after we are done
  251. using (SqlConnection connection = new SqlConnection(connectionString))
  252. {
  253. connection.Open();
  254. // Call the overload that takes a connection in place of the connection string
  255. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  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 == 0) throw new ArgumentNullException("connectionString");
  276. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  277. // If we receive parameter values, we need to figure out where they go
  278. if ((parameterValues != null) && (parameterValues.Length > 0))
  279. {
  280. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  281. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  282. // Assign the provided values to these parameters based on parameter order
  283. AssignParameterValues(commandParameters, parameterValues);
  284. // Call the overload that takes an array of SqlParameters
  285. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  286. }
  287. else
  288. {
  289. // Otherwise we can just call the SP without params
  290. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
  291. }
  292. }
  293. /// <summary>
  294. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
  295. /// </summary>
  296. /// <remarks>
  297. /// e.g.:
  298. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
  299. /// </remarks>
  300. /// <param name="connection">A valid SqlConnection</param>
  301. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  302. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  303. /// <returns>An int representing the number of rows affected by the command</returns>
  304. public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
  305. {
  306. // Pass through the call providing null for the set of SqlParameters
  307. return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
  308. }
  309. /// <summary>
  310. /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
  311. /// using the provided parameters.
  312. /// </summary>
  313. /// <remarks>
  314. /// e.g.:
  315. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  316. /// </remarks>
  317. /// <param name="connection">A valid SqlConnection</param>
  318. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  319. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  320. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  321. /// <returns>An int representing the number of rows affected by the command</returns>
  322. public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  323. {
  324. if (connection == null) throw new ArgumentNullException("connection");
  325. // Create a command and prepare it for execution
  326. SqlCommand cmd = new SqlCommand();
  327. bool mustCloseConnection = false;
  328. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  329. // Finally, execute the command
  330. int retval = cmd.ExecuteNonQuery();
  331. // Detach the SqlParameters from the command object, so they can be used again
  332. cmd.Parameters.Clear();
  333. if (mustCloseConnection)
  334. connection.Close();
  335. return retval;
  336. }
  337. /// <summary>
  338. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
  339. /// using the provided parameter values. This method will query the database to discover the parameters for the
  340. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  341. /// </summary>
  342. /// <remarks>
  343. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  344. ///
  345. /// e.g.:
  346. /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
  347. /// </remarks>
  348. /// <param name="connection">A valid SqlConnection</param>
  349. /// <param name="spName">The name of the stored procedure</param>
  350. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  351. /// <returns>An int representing the number of rows affected by the command</returns>
  352. public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
  353. {
  354. if (connection == null) throw new ArgumentNullException("connection");
  355. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  356. // If we receive parameter values, we need to figure out where they go
  357. if ((parameterValues != null) && (parameterValues.Length > 0))
  358. {
  359. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  360. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  361. // Assign the provided values to these parameters based on parameter order
  362. AssignParameterValues(commandParameters, parameterValues);
  363. // Call the overload that takes an array of SqlParameters
  364. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  365. }
  366. else
  367. {
  368. // Otherwise we can just call the SP without params
  369. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
  370. }
  371. }
  372. /// <summary>
  373. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
  374. /// </summary>
  375. /// <remarks>
  376. /// e.g.:
  377. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
  378. /// </remarks>
  379. /// <param name="transaction">A valid SqlTransaction</param>
  380. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  381. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  382. /// <returns>An int representing the number of rows affected by the command</returns>
  383. public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
  384. {
  385. // Pass through the call providing null for the set of SqlParameters
  386. return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
  387. }
  388. /// <summary>
  389. /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
  390. /// using the provided parameters.
  391. /// </summary>
  392. /// <remarks>
  393. /// e.g.:
  394. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  395. /// </remarks>
  396. /// <param name="transaction">A valid SqlTransaction</param>
  397. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  398. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  399. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  400. /// <returns>An int representing the number of rows affected by the command</returns>
  401. public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  402. {
  403. if (transaction == null) throw new ArgumentNullException("transaction");
  404. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  405. // Create a command and prepare it for execution
  406. SqlCommand cmd = new SqlCommand();
  407. bool mustCloseConnection = false;
  408. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  409. // Finally, execute the command
  410. int retval = cmd.ExecuteNonQuery();
  411. // Detach the SqlParameters from the command object, so they can be used again
  412. cmd.Parameters.Clear();
  413. return retval;
  414. }
  415. /// <summary>
  416. /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
  417. /// using the provided parameters.
  418. /// </summary>
  419. /// <remarks>
  420. /// e.g.:
  421. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  422. /// </remarks>
  423. /// <param name="transaction">A valid SqlTransaction</param>
  424. /// <param name="spName">The stored procedure name</param>
  425. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  426. /// <returns>An int representing the number of rows affected by the command</returns>
  427. public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params SqlParameter[] commandParameters)
  428. {
  429. if (transaction == null) throw new ArgumentNullException("transaction");
  430. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  431. // Create a command and prepare it for execution
  432. SqlCommand cmd = new SqlCommand();
  433. bool mustCloseConnection = false;
  434. PrepareCommand(cmd, transaction.Connection, transaction, CommandType.StoredProcedure, spName, commandParameters, out mustCloseConnection);
  435. // Finally, execute the command
  436. int retval = cmd.ExecuteNonQuery();
  437. // Detach the SqlParameters from the command object, so they can be used again
  438. cmd.Parameters.Clear();
  439. return retval;
  440. }
  441. /// <summary>
  442. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
  443. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  444. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  445. /// </summary>
  446. /// <remarks>
  447. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  448. ///
  449. /// e.g.:
  450. /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
  451. /// </remarks>
  452. /// <param name="transaction">A valid SqlTransaction</param>
  453. /// <param name="spName">The name of the stored procedure</param>
  454. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  455. /// <returns>An int representing the number of rows affected by the command</returns>
  456. public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
  457. {
  458. if (transaction == null) throw new ArgumentNullException("transaction");
  459. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  460. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  461. // If we receive parameter values, we need to figure out where they go
  462. if ((parameterValues != null) && (parameterValues.Length > 0))
  463. {
  464. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  465. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  466. // Assign the provided values to these parameters based on parameter order
  467. AssignParameterValues(commandParameters, parameterValues);
  468. // Call the overload that takes an array of SqlParameters
  469. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
  470. }
  471. else
  472. {
  473. // Otherwise we can just call the SP without params
  474. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
  475. }
  476. }
  477. #endregion ExecuteNonQuery
  478. #region ExecuteDataset
  479. /// <summary>
  480. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  481. /// the connection string.
  482. /// </summary>
  483. /// <remarks>
  484. /// e.g.:
  485. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
  486. /// </remarks>
  487. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  488. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  489. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  490. /// <returns>A dataset containing the resultset generated by the command</returns>
  491. public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
  492. {
  493. // Pass through the call providing null for the set of SqlParameters
  494. return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
  495. }
  496. /// <summary>
  497. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  498. /// using the provided parameters.
  499. /// </summary>
  500. /// <remarks>
  501. /// e.g.:
  502. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  503. /// </remarks>
  504. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  505. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  506. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  507. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  508. /// <returns>A dataset containing the resultset generated by the command</returns>
  509. public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  510. {
  511. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  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. // Call the overload that takes a connection in place of the connection string
  517. return ExecuteDataset(connection, commandType, commandText, commandParameters);
  518. }
  519. }
  520. /// <summary>
  521. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  522. /// using the provided parameters.
  523. /// </summary>
  524. /// <remarks>
  525. /// e.g.:
  526. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  527. /// </remarks>
  528. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  529. /// <param name="spName">The stored procedure name </param>
  530. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  531. /// <returns>A dataset containing the resultset generated by the command</returns>
  532. public static DataSet ExecuteDataset(string connectionString, string spName, params SqlParameter[] commandParameters)
  533. {
  534. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  535. // Create & open a SqlConnection, and dispose of it after we are done
  536. using (SqlConnection connection = new SqlConnection(connectionString))
  537. {
  538. connection.Open();
  539. // Call the overload that takes a connection in place of the connection string
  540. return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  541. }
  542. }
  543. /// <summary>
  544. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  545. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  546. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  547. /// </summary>
  548. /// <remarks>
  549. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  550. ///
  551. /// e.g.:
  552. /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
  553. /// </remarks>
  554. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  555. /// <param name="spName">The name of the stored procedure</param>
  556. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  557. /// <returns>A dataset containing the resultset generated by the command</returns>
  558. public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
  559. {
  560. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  561. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  562. // If we receive parameter values, we need to figure out where they go
  563. if ((parameterValues != null) && (parameterValues.Length > 0))
  564. {
  565. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  566. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  567. // Assign the provided values to these parameters based on parameter order
  568. AssignParameterValues(commandParameters, parameterValues);
  569. // Call the overload that takes an array of SqlParameters
  570. return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  571. }
  572. else
  573. {
  574. // Otherwise we can just call the SP without params
  575. return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  576. }
  577. }
  578. /// <summary>
  579. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  580. /// </summary>
  581. /// <remarks>
  582. /// e.g.:
  583. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
  584. /// </remarks>
  585. /// <param name="connection">A valid SqlConnection</param>
  586. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  587. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  588. /// <returns>A dataset containing the resultset generated by the command</returns>
  589. public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
  590. {
  591. // Pass through the call providing null for the set of SqlParameters
  592. return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
  593. }
  594. /// <summary>
  595. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  596. /// using the provided parameters.
  597. /// </summary>
  598. /// <remarks>
  599. /// e.g.:
  600. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  601. /// </remarks>
  602. /// <param name="connection">A valid SqlConnection</param>
  603. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  604. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  605. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  606. /// <returns>A dataset containing the resultset generated by the command</returns>
  607. public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  608. {
  609. if (connection == null) throw new ArgumentNullException("connection");
  610. // Create a command and prepare it for execution
  611. SqlCommand cmd = new SqlCommand();
  612. bool mustCloseConnection = false;
  613. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  614. // Create the DataAdapter & DataSet
  615. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  616. {
  617. DataSet ds = new DataSet();
  618. // Fill the DataSet using default values for DataTable names, etc
  619. da.Fill(ds);
  620. // Detach the SqlParameters from the command object, so they can be used again
  621. cmd.Parameters.Clear();
  622. if (mustCloseConnection)
  623. connection.Close();
  624. // Return the dataset
  625. return ds;
  626. }
  627. }
  628. /// <summary>
  629. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  630. /// using the provided parameter values. This method will query the database to discover the parameters for the
  631. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  632. /// </summary>
  633. /// <remarks>
  634. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  635. ///
  636. /// e.g.:
  637. /// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
  638. /// </remarks>
  639. /// <param name="connection">A valid SqlConnection</param>
  640. /// <param name="spName">The name of the stored procedure</param>
  641. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  642. /// <returns>A dataset containing the resultset generated by the command</returns>
  643. public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
  644. {
  645. if (connection == null) throw new ArgumentNullException("connection");
  646. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  647. // If we receive parameter values, we need to figure out where they go
  648. if ((parameterValues != null) && (parameterValues.Length > 0))
  649. {
  650. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  651. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  652. // Assign the provided values to these parameters based on parameter order
  653. AssignParameterValues(commandParameters, parameterValues);
  654. // Call the overload that takes an array of SqlParameters
  655. return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  656. }
  657. else
  658. {
  659. // Otherwise we can just call the SP without params
  660. return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
  661. }
  662. }
  663. /// <summary>
  664. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  665. /// </summary>
  666. /// <remarks>
  667. /// e.g.:
  668. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
  669. /// </remarks>
  670. /// <param name="transaction">A valid SqlTransaction</param>
  671. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  672. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  673. /// <returns>A dataset containing the resultset generated by the command</returns>
  674. public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
  675. {
  676. // Pass through the call providing null for the set of SqlParameters
  677. return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
  678. }
  679. /// <summary>
  680. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  681. /// using the provided parameters.
  682. /// </summary>
  683. /// <remarks>
  684. /// e.g.:
  685. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  686. /// </remarks>
  687. /// <param name="transaction">A valid SqlTransaction</param>
  688. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  689. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  690. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  691. /// <returns>A dataset containing the resultset generated by the command</returns>
  692. public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  693. {
  694. if (transaction == null) throw new ArgumentNullException("transaction");
  695. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  696. // Create a command and prepare it for execution
  697. SqlCommand cmd = new SqlCommand();
  698. bool mustCloseConnection = false;
  699. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  700. // Create the DataAdapter & DataSet
  701. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  702. {
  703. DataSet ds = new DataSet();
  704. // Fill the DataSet using default values for DataTable names, etc
  705. da.Fill(ds);
  706. // Detach the SqlParameters from the command object, so they can be used again
  707. cmd.Parameters.Clear();
  708. // Return the dataset
  709. return ds;
  710. }
  711. }
  712. /// <summary>
  713. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  714. /// using the provided parameters.
  715. /// </summary>
  716. /// <remarks>
  717. /// e.g.:
  718. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  719. /// </remarks>
  720. /// <param name="transaction">A valid SqlTransaction</param>
  721. /// <param name="spName">The stored procedure name </param>
  722. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  723. /// <returns>A dataset containing the resultset generated by the command</returns>
  724. public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params SqlParameter[] commandParameters)
  725. {
  726. if (transaction == null) throw new ArgumentNullException("transaction");
  727. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  728. // Create a command and prepare it for execution
  729. SqlCommand cmd = new SqlCommand();
  730. bool mustCloseConnection = false;
  731. PrepareCommand(cmd, transaction.Connection, transaction, CommandType.StoredProcedure, spName, commandParameters, out mustCloseConnection);
  732. // Create the DataAdapter & DataSet
  733. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  734. {
  735. DataSet ds = new DataSet();
  736. // Fill the DataSet using default values for DataTable names, etc
  737. da.Fill(ds);
  738. // Detach the SqlParameters from the command object, so they can be used again
  739. cmd.Parameters.Clear();
  740. // Return the dataset
  741. return ds;
  742. }
  743. }
  744. /// <summary>
  745. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  746. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  747. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  748. /// </summary>
  749. /// <remarks>
  750. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  751. ///
  752. /// e.g.:
  753. /// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
  754. /// </remarks>
  755. /// <param name="transaction">A valid SqlTransaction</param>
  756. /// <param name="spName">The name of the stored procedure</param>
  757. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  758. /// <returns>A dataset containing the resultset generated by the command</returns>
  759. public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
  760. {
  761. if (transaction == null) throw new ArgumentNullException("transaction");
  762. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  763. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  764. // If we receive parameter values, we need to figure out where they go
  765. if ((parameterValues != null) && (parameterValues.Length > 0))
  766. {
  767. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  768. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  769. // Assign the provided values to these parameters based on parameter order
  770. AssignParameterValues(commandParameters, parameterValues);
  771. // Call the overload that takes an array of SqlParameters
  772. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
  773. }
  774. else
  775. {
  776. // Otherwise we can just call the SP without params
  777. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
  778. }
  779. }
  780. #endregion ExecuteDataset
  781. #region ExecuteReader
  782. /// <summary>
  783. /// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
  784. /// we can set the appropriate CommandBehavior when calling ExecuteReader()
  785. /// </summary>
  786. private enum SqlConnectionOwnership
  787. {
  788. /// <summary>Connection is owned and managed by SqlHelper</summary>
  789. Internal,
  790. /// <summary>Connection is owned and managed by the caller</summary>
  791. External
  792. }
  793. /// <summary>
  794. /// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
  795. /// </summary>
  796. /// <remarks>
  797. /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
  798. ///
  799. /// If the caller provided the connection, we want to leave it to them to manage.
  800. /// </remarks>
  801. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  802. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  803. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  804. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  805. /// <param name="commandParameters">An array of S…

Large files files are truncated, but you can click here to view the full file