SQLHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. //===============================================================================
  2. // This file is based on the Microsoft Data Access Application Block for .NET
  3. // For more information please go to
  4. // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
  5. //===============================================================================
  6. using System;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.Collections;
  11. namespace Maticsoft.DBUtility
  12. {
  13. /// <summary>
  14. /// The SqlHelper class is intended to encapsulate high performance,
  15. /// scalable best practices for common uses of SqlClient.
  16. /// </summary>
  17. public abstract class SqlHelper
  18. {
  19. //Database connection strings
  20. public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.AppSettings["SQLConnString1"];
  21. public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.AppSettings["SQLConnString2"];
  22. public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.AppSettings["SQLConnString3"];
  23. public static readonly string ConnectionStringProfile = ConfigurationManager.AppSettings["SQLProfileConnString"];
  24. // Hashtable to store cached parameters
  25. private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
  26. /// <summary>
  27. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  28. /// using the provided parameters.
  29. /// </summary>
  30. /// <remarks>
  31. /// e.g.:
  32. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  33. /// </remarks>
  34. /// <param name="connectionString">a valid connection string for a SqlConnection</param>
  35. /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  36. /// <param name="commandText">the stored procedure name or T-SQL command</param>
  37. /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
  38. /// <returns>an int representing the number of rows affected by the command</returns>
  39. public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  40. {
  41. SqlCommand cmd = new SqlCommand();
  42. using (SqlConnection conn = new SqlConnection(connectionString))
  43. {
  44. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  45. int val = cmd.ExecuteNonQuery();
  46. cmd.Parameters.Clear();
  47. return val;
  48. }
  49. }
  50. /// <summary>
  51. /// Execute a SqlCommand (that returns no resultset) against an existing database connection
  52. /// using the provided parameters.
  53. /// </summary>
  54. /// <remarks>
  55. /// e.g.:
  56. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  57. /// </remarks>
  58. /// <param name="conn">an existing database connection</param>
  59. /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  60. /// <param name="commandText">the stored procedure name or T-SQL command</param>
  61. /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
  62. /// <returns>an int representing the number of rows affected by the command</returns>
  63. public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  64. {
  65. SqlCommand cmd = new SqlCommand();
  66. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  67. int val = cmd.ExecuteNonQuery();
  68. cmd.Parameters.Clear();
  69. return val;
  70. }
  71. /// <summary>
  72. /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
  73. /// using the provided parameters.
  74. /// </summary>
  75. /// <remarks>
  76. /// e.g.:
  77. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  78. /// </remarks>
  79. /// <param name="trans">an existing sql transaction</param>
  80. /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  81. /// <param name="commandText">the stored procedure name or T-SQL command</param>
  82. /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
  83. /// <returns>an int representing the number of rows affected by the command</returns>
  84. public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  85. {
  86. SqlCommand cmd = new SqlCommand();
  87. PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
  88. int val = cmd.ExecuteNonQuery();
  89. cmd.Parameters.Clear();
  90. return val;
  91. }
  92. /// <summary>
  93. /// Execute a SqlCommand that returns a resultset against the database specified in the connection string
  94. /// using the provided parameters.
  95. /// </summary>
  96. /// <remarks>
  97. /// e.g.:
  98. /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  99. /// </remarks>
  100. /// <param name="connectionString">a valid connection string for a SqlConnection</param>
  101. /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  102. /// <param name="commandText">the stored procedure name or T-SQL command</param>
  103. /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
  104. /// <returns>A SqlDataReader containing the results</returns>
  105. public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  106. {
  107. SqlCommand cmd = new SqlCommand();
  108. SqlConnection conn = new SqlConnection(connectionString);
  109. // we use a try/catch here because if the method throws an exception we want to
  110. // close the connection throw code, because no datareader will exist, hence the
  111. // commandBehaviour.CloseConnection will not work
  112. try
  113. {
  114. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  115. SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  116. cmd.Parameters.Clear();
  117. return rdr;
  118. }
  119. catch
  120. {
  121. conn.Close();
  122. throw;
  123. }
  124. }
  125. /// <summary>
  126. /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
  127. /// using the provided parameters.
  128. /// </summary>
  129. /// <remarks>
  130. /// e.g.:
  131. /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  132. /// </remarks>
  133. /// <param name="connectionString">a valid connection string for a SqlConnection</param>
  134. /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  135. /// <param name="commandText">the stored procedure name or T-SQL command</param>
  136. /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
  137. /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
  138. public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  139. {
  140. SqlCommand cmd = new SqlCommand();
  141. using (SqlConnection connection = new SqlConnection(connectionString))
  142. {
  143. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  144. object val = cmd.ExecuteScalar();
  145. cmd.Parameters.Clear();
  146. return val;
  147. }
  148. }
  149. /// <summary>
  150. /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
  151. /// using the provided parameters.
  152. /// </summary>
  153. /// <remarks>
  154. /// e.g.:
  155. /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  156. /// </remarks>
  157. /// <param name="conn">an existing database connection</param>
  158. /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
  159. /// <param name="commandText">the stored procedure name or T-SQL command</param>
  160. /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
  161. /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
  162. public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  163. {
  164. SqlCommand cmd = new SqlCommand();
  165. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  166. object val = cmd.ExecuteScalar();
  167. cmd.Parameters.Clear();
  168. return val;
  169. }
  170. /// <summary>
  171. /// add parameter array to the cache
  172. /// </summary>
  173. /// <param name="cacheKey">Key to the parameter cache</param>
  174. /// <param name="cmdParms">an array of SqlParamters to be cached</param>
  175. public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
  176. {
  177. parmCache[cacheKey] = commandParameters;
  178. }
  179. /// <summary>
  180. /// Retrieve cached parameters
  181. /// </summary>
  182. /// <param name="cacheKey">key used to lookup parameters</param>
  183. /// <returns>Cached SqlParamters array</returns>
  184. public static SqlParameter[] GetCachedParameters(string cacheKey)
  185. {
  186. SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
  187. if (cachedParms == null)
  188. return null;
  189. SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
  190. for (int i = 0, j = cachedParms.Length; i < j; i++)
  191. clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
  192. return clonedParms;
  193. }
  194. /// <summary>
  195. /// Prepare a command for execution
  196. /// </summary>
  197. /// <param name="cmd">SqlCommand object</param>
  198. /// <param name="conn">SqlConnection object</param>
  199. /// <param name="trans">SqlTransaction object</param>
  200. /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
  201. /// <param name="cmdText">Command text, e.g. Select * from Products</param>
  202. /// <param name="cmdParms">SqlParameters to use in the command</param>
  203. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
  204. {
  205. if (conn.State != ConnectionState.Open)
  206. conn.Open();
  207. cmd.Connection = conn;
  208. cmd.CommandText = cmdText;
  209. if (trans != null)
  210. cmd.Transaction = trans;
  211. cmd.CommandType = cmdType;
  212. if (cmdParms != null)
  213. {
  214. foreach (SqlParameter parm in cmdParms)
  215. cmd.Parameters.Add(parm);
  216. }
  217. }
  218. }
  219. }