SqlHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Collections;
  7. using System.Data.SqlClient;
  8. /// <summary>
  9. /// 数据库的通用访问代码
  10. /// 此类为抽象类,不允许实例化,在应用时直接调用即可
  11. /// </summary>
  12. public abstract class SqlHelper
  13. {
  14. //获取数据库连接字符串,其属于静态变量且只读,项目中所有文档可以直接使用,但不能修改
  15. public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;
  16. // 哈希表用来存储缓存的参数信息,哈希表可以存储任意类型的参数。
  17. private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
  18. /// <summary>
  19. ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
  20. /// 使用参数数组形式提供参数列表
  21. /// </summary>
  22. /// <remarks>
  23. /// 使用示例:
  24. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  25. /// </remarks>
  26. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  27. /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  28. /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
  29. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  30. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  31. public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  32. {
  33. SqlCommand cmd = new SqlCommand();
  34. using (SqlConnection conn = new SqlConnection(connectionString))
  35. {
  36. //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
  37. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  38. int val = cmd.ExecuteNonQuery();
  39. //清空SqlCommand中的参数列表
  40. cmd.Parameters.Clear();
  41. return val;
  42. }
  43. }
  44. /// <summary>
  45. ///执行一条不返回结果的SqlCommand,通过一个已经存在的数据库连接
  46. /// 使用参数数组提供参数
  47. /// </summary>
  48. /// <remarks>
  49. /// 使用示例:
  50. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  51. /// </remarks>
  52. /// <param name="conn">一个现有的数据库连接</param>
  53. /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  54. /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
  55. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  56. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  57. public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  58. {
  59. SqlCommand cmd = new SqlCommand();
  60. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  61. int val = cmd.ExecuteNonQuery();
  62. cmd.Parameters.Clear();
  63. return val;
  64. }
  65. /// <summary>
  66. /// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事物处理
  67. /// 使用参数数组提供参数
  68. /// </summary>
  69. /// <remarks>
  70. /// 使用示例:
  71. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  72. /// </remarks>
  73. /// <param name="trans">一个存在的 sql 事物处理</param>
  74. /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  75. /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
  76. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  77. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  78. public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  79. {
  80. SqlCommand cmd = new SqlCommand();
  81. PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
  82. int val = cmd.ExecuteNonQuery();
  83. cmd.Parameters.Clear();
  84. return val;
  85. }
  86. /// <summary>
  87. /// 执行一条返回结果集的SqlCommand命令,通过专用的连接字符串。
  88. /// 使用参数数组提供参数
  89. /// </summary>
  90. /// <remarks>
  91. /// 使用示例:
  92. /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  93. /// </remarks>
  94. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  95. /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  96. /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
  97. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  98. /// <returns>返回一个包含结果的SqlDataReader</returns>
  99. public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  100. {
  101. SqlCommand cmd = new SqlCommand();
  102. SqlConnection conn = new SqlConnection(connectionString);
  103. // 在这里使用try/catch处理是因为如果方法出现异常,则SqlDataReader就不存在,
  104. //CommandBehavior.CloseConnection的语句就不会执行,触发的异常由catch捕获。
  105. //关闭数据库连接,并通过throw再次引发捕捉到的异常。
  106. try
  107. {
  108. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  109. SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  110. cmd.Parameters.Clear();
  111. return rdr;
  112. }
  113. catch
  114. {
  115. conn.Close();
  116. throw;
  117. }
  118. }
  119. /// <summary>
  120. /// 执行一条返回第一条记录第一列的SqlCommand命令,通过专用的连接字符串。
  121. /// 使用参数数组提供参数
  122. /// </summary>
  123. /// <remarks>
  124. /// 使用示例:
  125. /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  126. /// </remarks>
  127. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  128. /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  129. /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
  130. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  131. /// <returns>返回一个object类型的数据,可以通过 Convert.To{Type}方法转换类型</returns>
  132. public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  133. {
  134. SqlCommand cmd = new SqlCommand();
  135. using (SqlConnection connection = new SqlConnection(connectionString))
  136. {
  137. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  138. object val = cmd.ExecuteScalar();
  139. cmd.Parameters.Clear();
  140. return val;
  141. }
  142. }
  143. /// <summary>
  144. /// 执行一条返回第一条记录第一列的SqlCommand命令,通过已经存在的数据库连接。
  145. /// 使用参数数组提供参数
  146. /// </summary>
  147. /// <remarks>
  148. /// 使用示例:
  149. /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  150. /// </remarks>
  151. /// <param name="conn">一个已经存在的数据库连接</param>
  152. /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  153. /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
  154. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  155. /// <returns>返回一个object类型的数据,可以通过 Convert.To{Type}方法转换类型</returns>
  156. public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  157. {
  158. SqlCommand cmd = new SqlCommand();
  159. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  160. object val = cmd.ExecuteScalar();
  161. cmd.Parameters.Clear();
  162. return val;
  163. }
  164. /// <summary>
  165. /// 缓存参数数组
  166. /// </summary>
  167. /// <param name="cacheKey">参数缓存的键值</param>
  168. /// <param name="cmdParms">被缓存的参数列表</param>
  169. public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
  170. {
  171. parmCache[cacheKey] = commandParameters;
  172. }
  173. /// <summary>
  174. /// 获取被缓存的参数
  175. /// </summary>
  176. /// <param name="cacheKey">用于查找参数的KEY值</param>
  177. /// <returns>返回缓存的参数数组</returns>
  178. public static SqlParameter[] GetCachedParameters(string cacheKey)
  179. {
  180. SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
  181. if (cachedParms == null)
  182. return null;
  183. //新建一个参数的克隆列表
  184. SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
  185. //通过循环为克隆参数列表赋值
  186. for (int i = 0, j = cachedParms.Length; i < j; i++)
  187. //使用clone方法复制参数列表中的参数
  188. clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
  189. return clonedParms;
  190. }
  191. /// <summary>
  192. /// 为执行命令准备参数
  193. /// </summary>
  194. /// <param name="cmd">SqlCommand 命令</param>
  195. /// <param name="conn">已经存在的数据库连接</param>
  196. /// <param name="trans">数据库事物处理</param>
  197. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  198. /// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param>
  199. /// <param name="cmdParms">返回带参数的命令</param>
  200. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
  201. {
  202. //判断数据库连接状态
  203. if (conn.State != ConnectionState.Open)
  204. conn.Open();
  205. cmd.Connection = conn;
  206. cmd.CommandText = cmdText;
  207. //判断是否需要事物处理
  208. if (trans != null)
  209. cmd.Transaction = trans;
  210. cmd.CommandType = cmdType;
  211. if (cmdParms != null)
  212. {
  213. foreach (SqlParameter parm in cmdParms)
  214. cmd.Parameters.Add(parm);
  215. }
  216. }
  217. /// <summary>
  218. /// 执行查询,返回结果集中的第一行第一列的值,忽略其他行列
  219. /// </summary>
  220. /// <param name="sql"></param>
  221. /// <returns></returns>
  222. public static object ExcuteScalar(string sql)
  223. {
  224. using (SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction))
  225. {
  226. con.Open();
  227. SqlCommand cmd = new SqlCommand(sql, con);
  228. con.Close();
  229. return cmd.ExecuteScalar();
  230. }
  231. }
  232. /// <summary>
  233. /// 执行查询
  234. /// </summary>
  235. /// <param name="sql">有效的sql语句</param>
  236. /// <param name="param">返回DataReader</param>
  237. /// <returns>返回DataReader</returns>
  238. public static SqlDataReader ExcuteReader(string sql, SqlParameter[] param)
  239. {
  240. SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction);
  241. con.Open();
  242. SqlCommand cmd = new SqlCommand(sql, con);
  243. cmd.Parameters.AddRange(param);
  244. SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  245. cmd.Parameters.Clear();
  246. return reader;
  247. }
  248. /// <summary>
  249. /// 执行查询
  250. /// </summary>
  251. /// <param name="sql">有效的sql语句</param>
  252. /// <returns>返回DataReader</returns>
  253. public static SqlDataReader ExcuteReader(string sql)
  254. {
  255. SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction);
  256. con.Open();
  257. SqlCommand cmd = new SqlCommand(sql, con);
  258. return cmd.ExecuteReader(CommandBehavior.CloseConnection);
  259. }
  260. /// <summary>
  261. /// 执行查询的基方法
  262. /// </summary>
  263. /// <param name="sql">有效的sql语句</param>
  264. /// <returns>返回DataTable</returns>
  265. public static DataTable ExcuteDataQuery(string sql)
  266. {
  267. using (SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction))
  268. {
  269. con.Open();
  270. SqlDataAdapter sda = new SqlDataAdapter(sql, con);
  271. DataTable table = new DataTable();
  272. sda.Fill(table);
  273. con.Close();
  274. return table;
  275. }
  276. }
  277. /// <summary>
  278. /// 执行增,删,改的基方法
  279. /// </summary>
  280. /// <param name="sql">有效的sql语句</param>
  281. /// <param name="param">参数集合</param>
  282. /// <returns>影响的行数</returns>
  283. public static int ExcuteNonQuery(string sql, SqlParameter[] param)
  284. {
  285. using (SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction))
  286. {
  287. con.Open();
  288. SqlCommand cmd = new SqlCommand(sql, con);
  289. if (param != null)
  290. {
  291. cmd.Parameters.AddRange(param);
  292. }
  293. int count = cmd.ExecuteNonQuery();
  294. cmd.Parameters.Clear();
  295. con.Close();
  296. return count;
  297. }
  298. }
  299. //每页显示5条数据
  300. static int pageSize = 10;
  301. /// <summary>
  302. /// 查询共有多少行,然后直接返回总页码
  303. /// </summary>
  304. /// <returns></returns>
  305. public static int GetAllBookCount()
  306. {
  307. int num = 0;
  308. int pageCount = 0;
  309. string sql = "select count(0) from TB_BookInfo";
  310. num = Convert.ToInt32(ExcuteScalar(sql));
  311. pageCount = num % pageSize != 0 ? (num / pageSize) + 1 : num / pageSize;
  312. return pageCount;
  313. }
  314. /// <summary>
  315. /// 准备命令
  316. /// </summary>
  317. /// <param name="con"></param>
  318. /// <param name="cmd"></param>
  319. /// <param name="textcmd"></param>
  320. /// <param name="cmdType"></param>
  321. /// <param name="param"></param>
  322. public static void PreparedCommd(SqlConnection con, SqlCommand cmd, string textcmd, CommandType cmdType, SqlParameter[] param)
  323. {
  324. try
  325. {
  326. if (con.State != ConnectionState.Open)
  327. {
  328. con.Open();
  329. }
  330. cmd.Connection = con;
  331. cmd.CommandText = textcmd;
  332. cmd.CommandType = cmdType;
  333. if (param != null)
  334. {
  335. foreach (SqlParameter p in param)
  336. {
  337. cmd.Parameters.Add(p);
  338. }
  339. }
  340. }
  341. catch (Exception ex)
  342. {
  343. throw new Exception(ex.Message);
  344. }
  345. }
  346. /// <summary>
  347. /// 执行增、删、改
  348. /// </summary>
  349. /// <param name="textcmd">sql语句或者存储过程</param>
  350. /// <param name="cmdType">类型</param>
  351. /// <param name="param">参数</param>
  352. /// <returns>返回int类型的数据</returns>
  353. public static int ExecuteNonQuery(string textcmd,SqlParameter[] param, CommandType cmdType)
  354. {
  355. using (SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction))
  356. {
  357. SqlCommand cmd = new SqlCommand();
  358. PreparedCommd(con, cmd, textcmd, cmdType, param);
  359. int num = cmd.ExecuteNonQuery();
  360. return num;
  361. }
  362. }
  363. /// <summary>
  364. /// 读取一行一列的数据
  365. /// </summary>
  366. /// <param name="textmd"></param>
  367. /// <param name="cmdType"></param>
  368. /// <param name="param"></param>
  369. /// <returns></returns>
  370. public static object ExecuteScalar(string textmd, CommandType cmdType, SqlParameter[] param)
  371. {
  372. using (SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction))
  373. {
  374. SqlCommand cmd = new SqlCommand();
  375. PreparedCommd(con, cmd, textmd, cmdType, param);
  376. return cmd.ExecuteScalar();
  377. }
  378. }
  379. /// <summary>
  380. /// 读取一行一列的数据
  381. /// </summary>
  382. /// <param name="textmd"></param>
  383. /// <param name="cmdType"></param>
  384. /// <param name="param"></param>
  385. /// <returns></returns>
  386. public static object ExecuteScalar(string SQL)
  387. {
  388. using (SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction))
  389. {
  390. con.Open();
  391. SqlCommand cmd = new SqlCommand(SQL, con);
  392. return cmd.ExecuteScalar();
  393. }
  394. }
  395. /// <summary>
  396. /// 查询
  397. /// </summary>
  398. /// <param name="textcmd"></param>
  399. /// <param name="cmdType"></param>
  400. /// <param name="param"></param>
  401. /// <returns></returns>
  402. public static SqlDataReader ExecuteReader(string textcmd, CommandType cmdType, SqlParameter[] param)
  403. {
  404. SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction);
  405. SqlCommand cmd = new SqlCommand();
  406. try
  407. {
  408. //PreparedCommd(con, cmd, textcmd, cmdType, param);
  409. SqlDataReader read = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  410. return read;
  411. }
  412. catch (Exception ex)
  413. {
  414. con.Close();
  415. throw new Exception(ex.Message);
  416. }
  417. }
  418. /// <summary>
  419. /// 查询返回DataTable
  420. /// </summary>
  421. /// <param name="sql"></param>
  422. /// <returns></returns>
  423. public static DataTable ExecuteReader(string sql)
  424. {
  425. SqlConnection con = new SqlConnection(ConnectionStringLocalTransaction);
  426. DataTable dt = new DataTable();
  427. try
  428. {
  429. SqlDataAdapter da = new SqlDataAdapter(sql, con);
  430. da.Fill(dt);
  431. }
  432. catch (Exception)
  433. {
  434. throw;
  435. }
  436. return dt;
  437. }
  438. /// <summary>
  439. /// 用户登录
  440. /// </summary>
  441. /// <param name="UserName"></param>
  442. /// <param name="UserPwd"></param>
  443. /// <returns></returns>
  444. public static int CheckLogin(string UserName, string UserPwd)
  445. {
  446. int num = 0;
  447. try
  448. {
  449. string sql = "select * from TB_UserInfo where [user_Name]='" + UserName + "' and user_pwd='" + UserPwd + "'";
  450. num = Convert.ToInt32(ExecuteScalar(sql));
  451. }
  452. catch (Exception ex)
  453. {
  454. throw ex;
  455. }
  456. return num;
  457. }
  458. }