SqlHelper.cs 146 KB

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