华恒Mes鼎捷代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2713 lines
158 KiB

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