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

905 lines
35 KiB

2 years ago
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. namespace EasyNet.DBUtility
  7. {
  8. public abstract class DbHelperSQL
  9. {
  10. //資料庫連接字符串(web.config來配置),可以動態改變connectionString支持多資料庫.
  11. private static string _connectionString = AdoHelper.ConnectionString;
  12. protected DbHelperSQL()
  13. {
  14. }
  15. #region 公用方法
  16. /// <summary>
  17. /// 判斷是否存在某表的某個欄位
  18. /// </summary>
  19. /// <param name="tableName">表名稱</param>
  20. /// <param name="columnName">欄位名稱</param>
  21. /// <returns>是否存在</returns>
  22. public static bool ColumnExists(string tableName, string columnName)
  23. {
  24. var sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
  25. var res = GetSingle(sql);
  26. if (res == null)
  27. {
  28. return false;
  29. }
  30. return Convert.ToInt32(res) > 0;
  31. }
  32. public static int GetMaxID(string FieldName, string TableName)
  33. {
  34. var strsql = "select max(" + FieldName + ")+1 from " + TableName;
  35. var obj = DbHelperSQL.GetSingle(strsql);
  36. return obj == null ? 1 : int.Parse(obj.ToString());
  37. }
  38. public static bool Exists(string strSql)
  39. {
  40. var obj = DbHelperSQL.GetSingle(strSql);
  41. int cmdresult;
  42. cmdresult = (Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)) ? 0 : int.Parse(obj.ToString());
  43. return cmdresult == 0 ? false : true;
  44. }
  45. /// <summary>
  46. /// 表是否存在
  47. /// </summary>
  48. /// <param name="TableName"></param>
  49. /// <returns></returns>
  50. public static bool TabExists(string TableName)
  51. {
  52. var strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
  53. //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
  54. var obj = DbHelperSQL.GetSingle(strsql);
  55. int cmdresult;
  56. cmdresult = (Object.Equals(obj, null)) || (Object.Equals(obj, DBNull.Value)) ? 0 : int.Parse(obj.ToString());
  57. return cmdresult == 0 ? false : true;
  58. }
  59. public static bool Exists(string strSql, params SqlParameter[] cmdParms)
  60. {
  61. var obj = DbHelperSQL.GetSingle(strSql, cmdParms);
  62. int cmdresult;
  63. cmdresult = (Object.Equals(obj, null)) || (Object.Equals(obj, DBNull.Value)) ? 0 : int.Parse(obj.ToString());
  64. return cmdresult == 0 ? false : true;
  65. }
  66. #endregion 公用方法
  67. #region 執行簡單SQL語句
  68. /// <summary>
  69. /// 執行SQL語句,返回影響的資料數
  70. /// </summary>
  71. /// <param name="SQLString">SQL語句</param>
  72. /// <returns>影響的資料數</returns>
  73. public static int ExecuteSql(string SQLString)
  74. {
  75. using (SqlConnection connection = new SqlConnection(_connectionString))
  76. {
  77. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  78. {
  79. try
  80. {
  81. connection.Open();
  82. var rows = cmd.ExecuteNonQuery();
  83. return rows;
  84. }
  85. catch (SqlException e)
  86. {
  87. connection.Close();
  88. throw new Exception("some reason to rethrow", e);
  89. }
  90. finally
  91. {
  92. cmd.Dispose();
  93. connection.Close();
  94. }
  95. }
  96. }
  97. }
  98. public static int ExecuteSqlByTime(string SQLString, int Times)
  99. {
  100. using (SqlConnection connection = new SqlConnection(_connectionString))
  101. {
  102. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  103. {
  104. try
  105. {
  106. connection.Open();
  107. cmd.CommandTimeout = Times;
  108. var rows = cmd.ExecuteNonQuery();
  109. return rows;
  110. }
  111. catch (SqlException e)
  112. {
  113. connection.Close();
  114. throw new Exception("some reason to rethrow", e);
  115. }
  116. finally
  117. {
  118. cmd.Dispose();
  119. connection.Close();
  120. }
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// 執行多条SQL語句,實現資料庫事務。
  126. /// </summary>
  127. /// <param name="SQLStringList">多条SQL語句</param>
  128. public static int ExecuteSqlTran(List<String> SQLStringList)
  129. {
  130. using (SqlConnection connection = new SqlConnection(_connectionString))
  131. {
  132. connection.Open();
  133. var cmd = new SqlCommand
  134. {
  135. Connection = connection
  136. };
  137. var tx = connection.BeginTransaction();
  138. cmd.Transaction = tx;
  139. try
  140. {
  141. var count = 0;
  142. foreach (var strsql in SQLStringList)
  143. {
  144. if (strsql.Trim().Length > 1)
  145. {
  146. cmd.CommandText = strsql;
  147. count += cmd.ExecuteNonQuery();
  148. }
  149. }
  150. tx.Commit();
  151. return count;
  152. }
  153. catch (Exception)
  154. {
  155. tx.Rollback();
  156. return 0;
  157. }
  158. finally
  159. {
  160. cmd.Dispose();
  161. connection.Close();
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// 執行带一個存储過程参數的的SQL語句。
  167. /// </summary>
  168. /// <param name="SQLString">SQL語句</param>
  169. /// <param name="content">参數内容,比如一個欄位是格式複雜的文章,有特殊符號,可以通過這個方式添加</param>
  170. /// <returns>影響的資料數</returns>
  171. public static int ExecuteSql(string SQLString, string content)
  172. {
  173. using (SqlConnection connection = new SqlConnection(_connectionString))
  174. {
  175. var cmd = new SqlCommand(SQLString, connection);
  176. var myParameter = new SqlParameter("@content", SqlDbType.NText)
  177. {
  178. Value = content
  179. };
  180. cmd.Parameters.Add(myParameter);
  181. try
  182. {
  183. connection.Open();
  184. var rows = cmd.ExecuteNonQuery();
  185. return rows;
  186. }
  187. catch (SqlException e)
  188. {
  189. throw new Exception("some reason to rethrow", e);
  190. }
  191. finally
  192. {
  193. cmd.Dispose();
  194. connection.Close();
  195. }
  196. }
  197. }
  198. /// <summary>
  199. /// 執行带一個存储過程参數的的SQL語句。
  200. /// </summary>
  201. /// <param name="SQLString">SQL語句</param>
  202. /// <param name="content">参數内容,比如一個欄位是格式複雜的文章,有特殊符號,可以通過這個方式添加</param>
  203. /// <returns>影響的資料數</returns>
  204. public static object ExecuteSqlGet(string SQLString, string content)
  205. {
  206. using (SqlConnection connection = new SqlConnection(_connectionString))
  207. {
  208. var cmd = new SqlCommand(SQLString, connection);
  209. var myParameter = new SqlParameter("@content", SqlDbType.NText)
  210. {
  211. Value = content
  212. };
  213. cmd.Parameters.Add(myParameter);
  214. try
  215. {
  216. connection.Open();
  217. var obj = cmd.ExecuteScalar();
  218. return (Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)) ? null : obj;
  219. }
  220. catch (SqlException e)
  221. {
  222. throw new Exception("some reason to rethrow", e);
  223. }
  224. finally
  225. {
  226. cmd.Dispose();
  227. connection.Close();
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// 向資料庫里插入圖像格式的欄位(和上面情況類似的另一種實例)
  233. /// </summary>
  234. /// <param name="strSQL">SQL語句</param>
  235. /// <param name="fs">圖像字節,資料庫的欄位類型为image的情況</param>
  236. /// <returns>影響的資料數</returns>
  237. public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
  238. {
  239. using (SqlConnection connection = new SqlConnection(_connectionString))
  240. {
  241. var cmd = new SqlCommand(strSQL, connection);
  242. var myParameter = new SqlParameter("@fs", SqlDbType.Image)
  243. {
  244. Value = fs
  245. };
  246. cmd.Parameters.Add(myParameter);
  247. try
  248. {
  249. connection.Open();
  250. var rows = cmd.ExecuteNonQuery();
  251. return rows;
  252. }
  253. catch (SqlException e)
  254. {
  255. throw new Exception("some reason to rethrow", e);
  256. }
  257. finally
  258. {
  259. cmd.Dispose();
  260. connection.Close();
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// 執行一条计算查詢結果語句,返回查詢結果{Object}。
  266. /// </summary>
  267. /// <param name="SQLString">计算查詢結果語句</param>
  268. /// <returns>查詢結果{Object}</returns>
  269. public static object GetSingle(string SQLString)
  270. {
  271. using (SqlConnection connection = new SqlConnection(_connectionString))
  272. {
  273. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  274. {
  275. try
  276. {
  277. connection.Open();
  278. var obj = cmd.ExecuteScalar();
  279. return (Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)) ? null : obj;
  280. }
  281. catch (SqlException e)
  282. {
  283. connection.Close();
  284. throw new Exception("some reason to rethrow", e);
  285. }
  286. finally
  287. {
  288. cmd.Dispose();
  289. connection.Close();
  290. }
  291. }
  292. }
  293. }
  294. public static object GetSingle(string SQLString, int Times)
  295. {
  296. using (SqlConnection connection = new SqlConnection(_connectionString))
  297. {
  298. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  299. {
  300. try
  301. {
  302. connection.Open();
  303. cmd.CommandTimeout = Times;
  304. var obj = cmd.ExecuteScalar();
  305. return (Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)) ? null : obj;
  306. }
  307. catch (SqlException e)
  308. {
  309. connection.Close();
  310. throw new Exception("some reason to rethrow", e);
  311. }
  312. finally
  313. {
  314. cmd.Dispose();
  315. connection.Close();
  316. }
  317. }
  318. }
  319. }
  320. /// <summary>
  321. /// 執行查詢語句,返回SqlDataReader ( 注意:調用該方法後,一定要對SqlDataReader進行Close )
  322. /// </summary>
  323. /// <param name="strSQL">查詢語句</param>
  324. /// <returns>SqlDataReader</returns>
  325. public static SqlDataReader ExecuteReader(string strSQL)
  326. {
  327. var connection = new SqlConnection(_connectionString);
  328. using (var cmd = new SqlCommand(strSQL, connection))
  329. {
  330. try
  331. {
  332. connection.Open();
  333. var myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  334. return myReader;
  335. }
  336. catch (SqlException e)
  337. {
  338. throw new Exception("some reason to rethrow", e);
  339. }
  340. }
  341. }
  342. /// <summary>
  343. /// 執行查詢語句,返回DataSet
  344. /// </summary>
  345. /// <param name="SQLString">查詢語句</param>
  346. /// <returns>DataSet</returns>
  347. public static DataSet Query(string SQLString)
  348. {
  349. using (SqlConnection connection = new SqlConnection(_connectionString))
  350. {
  351. var ds = new DataSet();
  352. try
  353. {
  354. connection.Open();
  355. using (var command = new SqlDataAdapter(SQLString, connection))
  356. {
  357. command.Fill(ds, nameof(ds));
  358. }
  359. }
  360. catch (SqlException ex)
  361. {
  362. throw new Exception(ex.Message);
  363. }
  364. finally
  365. {
  366. connection.Close();
  367. }
  368. return ds;
  369. }
  370. }
  371. public static DataSet Query(string SQLString, int Times)
  372. {
  373. using (SqlConnection connection = new SqlConnection(_connectionString))
  374. {
  375. var ds = new DataSet();
  376. try
  377. {
  378. connection.Open();
  379. using (var command = new SqlDataAdapter(SQLString, connection))
  380. {
  381. command.SelectCommand.CommandTimeout = Times;
  382. command.Fill(ds, nameof(ds));
  383. }
  384. }
  385. catch (SqlException ex)
  386. {
  387. throw new Exception(ex.Message);
  388. }
  389. finally
  390. {
  391. connection.Close();
  392. }
  393. return ds;
  394. }
  395. }
  396. #endregion 執行簡單SQL語句
  397. #region 執行带参數的SQL語句
  398. /// <summary>
  399. /// 執行SQL語句,返回影響的資料數
  400. /// </summary>
  401. /// <param name="SQLString">SQL語句</param>
  402. /// <param name="cmdParms">todo: describe cmdParms parameter on ExecuteSql</param>
  403. /// <returns>影響的資料數</returns>
  404. public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
  405. {
  406. using (SqlConnection connection = new SqlConnection(_connectionString))
  407. {
  408. using (SqlCommand cmd = new SqlCommand())
  409. {
  410. try
  411. {
  412. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  413. var rows = cmd.ExecuteNonQuery();
  414. cmd.Parameters.Clear();
  415. return rows;
  416. }
  417. catch (SqlException e)
  418. {
  419. throw new Exception("some reason to rethrow", e);
  420. }
  421. finally
  422. {
  423. cmd.Dispose();
  424. connection.Close();
  425. }
  426. }
  427. }
  428. }
  429. /// <summary>
  430. /// 執行多条SQL語句,實現資料庫事務。
  431. /// </summary>
  432. /// <param name="SQLStringList">SQL語句的哈希表(key为sql語句,value是該語句的SqlParameter[])</param>
  433. public static void ExecuteSqlTran(Hashtable SQLStringList)
  434. {
  435. using (SqlConnection conn = new SqlConnection(_connectionString))
  436. {
  437. conn.Open();
  438. using (SqlTransaction trans = conn.BeginTransaction())
  439. {
  440. var cmd = new SqlCommand();
  441. try
  442. {
  443. //循環
  444. foreach (DictionaryEntry myDE in SQLStringList)
  445. {
  446. var cmdText = myDE.Key.ToString();
  447. var cmdParms = (SqlParameter[])myDE.Value;
  448. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  449. var val = cmd.ExecuteNonQuery();
  450. cmd.Parameters.Clear();
  451. }
  452. trans.Commit();
  453. }
  454. catch
  455. {
  456. trans.Rollback();
  457. throw;
  458. }
  459. }
  460. }
  461. }
  462. /// <summary>
  463. /// 執行多条SQL語句,實現資料庫事務。
  464. /// </summary>
  465. /// <param name="cmdList">todo: describe cmdList parameter on ExecuteSqlTran</param>
  466. public static int ExecuteSqlTran(List<CommandInfo> cmdList)
  467. {
  468. using (SqlConnection conn = new SqlConnection(_connectionString))
  469. {
  470. conn.Open();
  471. using (SqlTransaction trans = conn.BeginTransaction())
  472. {
  473. var cmd = new SqlCommand();
  474. try
  475. {
  476. var count = 0;
  477. //循環
  478. foreach (CommandInfo myDE in cmdList)
  479. {
  480. var cmdText = myDE.CommandText;
  481. var cmdParms = (SqlParameter[])myDE.Parameters;
  482. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  483. if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
  484. {
  485. if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
  486. {
  487. trans.Rollback();
  488. return 0;
  489. }
  490. var obj = cmd.ExecuteScalar();
  491. var isHave = false;
  492. if (obj == null && obj == DBNull.Value)
  493. {
  494. isHave = false;
  495. }
  496. isHave = Convert.ToInt32(obj) > 0;
  497. if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
  498. {
  499. trans.Rollback();
  500. return 0;
  501. }
  502. if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
  503. {
  504. trans.Rollback();
  505. return 0;
  506. }
  507. continue;
  508. }
  509. var val = cmd.ExecuteNonQuery();
  510. count += val;
  511. if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
  512. {
  513. trans.Rollback();
  514. return 0;
  515. }
  516. cmd.Parameters.Clear();
  517. }
  518. trans.Commit();
  519. return count;
  520. }
  521. catch
  522. {
  523. trans.Rollback();
  524. throw;
  525. }
  526. }
  527. }
  528. }
  529. /// <summary>
  530. /// 執行多条SQL語句,實現資料庫事務。
  531. /// </summary>
  532. /// <param name="SQLStringList">SQL語句的哈希表(key为sql語句,value是該語句的SqlParameter[])</param>
  533. public static void ExecuteSqlTranWithIndentity(List<CommandInfo> SQLStringList)
  534. {
  535. using (SqlConnection conn = new SqlConnection(_connectionString))
  536. {
  537. conn.Open();
  538. using (SqlTransaction trans = conn.BeginTransaction())
  539. {
  540. var cmd = new SqlCommand();
  541. try
  542. {
  543. var indentity = 0;
  544. //循環
  545. foreach (CommandInfo myDE in SQLStringList)
  546. {
  547. var cmdText = myDE.CommandText;
  548. var cmdParms = (SqlParameter[])myDE.Parameters;
  549. foreach (SqlParameter q in cmdParms)
  550. {
  551. if (q.Direction == ParameterDirection.InputOutput)
  552. {
  553. q.Value = indentity;
  554. }
  555. }
  556. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  557. var val = cmd.ExecuteNonQuery();
  558. foreach (SqlParameter q in cmdParms)
  559. {
  560. if (q.Direction == ParameterDirection.Output)
  561. {
  562. indentity = Convert.ToInt32(q.Value);
  563. }
  564. }
  565. cmd.Parameters.Clear();
  566. }
  567. trans.Commit();
  568. }
  569. catch
  570. {
  571. trans.Rollback();
  572. throw;
  573. }
  574. }
  575. }
  576. }
  577. /// <summary>
  578. /// 執行多条SQL語句,實現資料庫事務。
  579. /// </summary>
  580. /// <param name="SQLStringList">SQL語句的哈希表(key为sql語句,value是該語句的SqlParameter[])</param>
  581. public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
  582. {
  583. using (SqlConnection conn = new SqlConnection(_connectionString))
  584. {
  585. conn.Open();
  586. using (SqlTransaction trans = conn.BeginTransaction())
  587. {
  588. var cmd = new SqlCommand();
  589. try
  590. {
  591. var indentity = 0;
  592. //循環
  593. foreach (DictionaryEntry myDE in SQLStringList)
  594. {
  595. var cmdText = myDE.Key.ToString();
  596. var cmdParms = (SqlParameter[])myDE.Value;
  597. foreach (SqlParameter q in cmdParms)
  598. {
  599. if (q.Direction == ParameterDirection.InputOutput)
  600. {
  601. q.Value = indentity;
  602. }
  603. }
  604. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  605. var val = cmd.ExecuteNonQuery();
  606. foreach (SqlParameter q in cmdParms)
  607. {
  608. if (q.Direction == ParameterDirection.Output)
  609. {
  610. indentity = Convert.ToInt32(q.Value);
  611. }
  612. }
  613. cmd.Parameters.Clear();
  614. }
  615. trans.Commit();
  616. }
  617. catch
  618. {
  619. trans.Rollback();
  620. throw;
  621. }
  622. }
  623. }
  624. }
  625. /// <summary>
  626. /// 執行一条计算查詢結果語句,返回查詢結果{Object}。
  627. /// </summary>
  628. /// <param name="SQLString">计算查詢結果語句</param>
  629. /// <param name="cmdParms">todo: describe cmdParms parameter on GetSingle</param>
  630. /// <returns>查詢結果{Object}</returns>
  631. public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
  632. {
  633. using (SqlConnection connection = new SqlConnection(_connectionString))
  634. {
  635. using (SqlCommand cmd = new SqlCommand())
  636. {
  637. try
  638. {
  639. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  640. var obj = cmd.ExecuteScalar();
  641. cmd.Parameters.Clear();
  642. return (Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)) ? null : obj;
  643. }
  644. catch (SqlException e)
  645. {
  646. throw new Exception("some reason to rethrow", e);
  647. }
  648. finally
  649. {
  650. cmd.Dispose();
  651. connection.Close();
  652. }
  653. }
  654. }
  655. }
  656. /// <summary>
  657. /// 執行查詢語句,返回SqlDataReader ( 注意:調用該方法後,一定要對SqlDataReader進行Close )
  658. /// </summary>
  659. /// <param name="SQLString">todo: describe SQLString parameter on ExecuteReader</param>
  660. /// <param name="cmdParms">todo: describe cmdParms parameter on ExecuteReader</param>
  661. /// <returns>SqlDataReader</returns>
  662. public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
  663. {
  664. var connection = new SqlConnection(_connectionString);
  665. var cmd = new SqlCommand();
  666. try
  667. {
  668. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  669. var myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  670. cmd.Parameters.Clear();
  671. return myReader;
  672. }
  673. catch (SqlException e)
  674. {
  675. throw new Exception("some reason to rethrow", e);
  676. }
  677. }
  678. /// <summary>
  679. /// 執行查詢語句,返回DataSet
  680. /// </summary>
  681. /// <param name="SQLString">查詢語句</param>
  682. /// <param name="cmdParms">todo: describe cmdParms parameter on Query</param>
  683. /// <returns>DataSet</returns>
  684. public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
  685. {
  686. using (SqlConnection connection = new SqlConnection(_connectionString))
  687. {
  688. var cmd = new SqlCommand();
  689. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  690. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  691. {
  692. var ds = new DataSet();
  693. try
  694. {
  695. da.Fill(ds, nameof(ds));
  696. cmd.Parameters.Clear();
  697. }
  698. catch (SqlException ex)
  699. {
  700. throw new Exception(ex.Message);
  701. }
  702. finally
  703. {
  704. cmd.Dispose();
  705. connection.Close();
  706. }
  707. return ds;
  708. }
  709. }
  710. }
  711. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  712. {
  713. if (conn.State != ConnectionState.Open)
  714. conn.Open();
  715. cmd.Connection = conn;
  716. cmd.CommandText = cmdText;
  717. if (trans != null)
  718. cmd.Transaction = trans;
  719. if (cmdText.StartsWith("OSP_"))
  720. cmd.CommandType = CommandType.StoredProcedure;//cmdType;
  721. else
  722. cmd.CommandType = CommandType.Text;//cmdType;
  723. if (cmdParms != null)
  724. {
  725. foreach (SqlParameter parameter in cmdParms)
  726. {
  727. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  728. (parameter.Value == null))
  729. {
  730. parameter.Value = DBNull.Value;
  731. }
  732. cmd.Parameters.Add(parameter);
  733. }
  734. }
  735. }
  736. #endregion 執行带参數的SQL語句
  737. #region 存储過程操作
  738. /// <summary>
  739. /// 執行存储過程,返回SqlDataReader ( 注意:調用該方法後,一定要對SqlDataReader進行Close )
  740. /// </summary>
  741. /// <param name="storedProcName">存储過程名</param>
  742. /// <param name="parameters">存储過程参數</param>
  743. /// <returns>SqlDataReader</returns>
  744. public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
  745. {
  746. var connection = new SqlConnection(_connectionString);
  747. SqlDataReader returnReader;
  748. connection.Open();
  749. var command = BuildQueryCommand(connection, storedProcName, parameters);
  750. command.CommandType = CommandType.StoredProcedure;
  751. returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
  752. return returnReader;
  753. }
  754. /// <summary>
  755. /// 執行存储過程
  756. /// </summary>
  757. /// <param name="storedProcName">存储過程名</param>
  758. /// <param name="parameters">存储過程参數</param>
  759. /// <param name="tableName">DataSet結果中的表名</param>
  760. /// <returns>DataSet</returns>
  761. public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
  762. {
  763. using (SqlConnection connection = new SqlConnection(_connectionString))
  764. {
  765. var dataSet = new DataSet();
  766. connection.Open();
  767. using (var sqlDA = new SqlDataAdapter
  768. {
  769. SelectCommand = BuildQueryCommand(connection, storedProcName, parameters)
  770. })
  771. {
  772. sqlDA.Fill(dataSet, tableName);
  773. connection.Close();
  774. return dataSet;
  775. }
  776. }
  777. }
  778. public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
  779. {
  780. using (SqlConnection connection = new SqlConnection(_connectionString))
  781. {
  782. var dataSet = new DataSet();
  783. connection.Open();
  784. using (var sqlDA = new SqlDataAdapter
  785. {
  786. SelectCommand = BuildQueryCommand(connection, storedProcName, parameters)
  787. })
  788. {
  789. sqlDA.SelectCommand.CommandTimeout = Times;
  790. sqlDA.Fill(dataSet, tableName);
  791. connection.Close();
  792. return dataSet;
  793. }
  794. }
  795. }
  796. /// <summary>
  797. /// 构建 SqlCommand 對象(用來返回一個結果集,而不是一個整數值)
  798. /// </summary>
  799. /// <param name="connection">資料庫連接</param>
  800. /// <param name="storedProcName">存储過程名</param>
  801. /// <param name="parameters">存储過程参數</param>
  802. /// <returns>SqlCommand</returns>
  803. private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  804. {
  805. var command = new SqlCommand(storedProcName, connection)
  806. {
  807. CommandType = CommandType.StoredProcedure
  808. };
  809. foreach (SqlParameter parameter in parameters)
  810. {
  811. if (parameter != null)
  812. {
  813. // 檢查未分配值的輸出参數,将其分配以DBNull.Value.
  814. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  815. (parameter.Value == null))
  816. {
  817. parameter.Value = DBNull.Value;
  818. }
  819. command.Parameters.Add(parameter);
  820. }
  821. }
  822. return command;
  823. }
  824. /// <summary>
  825. /// 執行存储過程,返回影響的行數
  826. /// </summary>
  827. /// <param name="storedProcName">存储過程名</param>
  828. /// <param name="parameters">存储過程参數</param>
  829. /// <param name="rowsAffected">影響的行數</param>
  830. /// <returns></returns>
  831. public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
  832. {
  833. using (SqlConnection connection = new SqlConnection(_connectionString))
  834. {
  835. int result;
  836. connection.Open();
  837. var command = BuildIntCommand(connection, storedProcName, parameters);
  838. rowsAffected = command.ExecuteNonQuery();
  839. result = (int)command.Parameters["ReturnValue"].Value;
  840. //Connection.Close();
  841. return result;
  842. }
  843. }
  844. /// <summary>
  845. /// 創建 SqlCommand 對象實例(用來返回一個整數值)
  846. /// </summary>
  847. /// <param name="storedProcName">存储過程名</param>
  848. /// <param name="parameters">存储過程参數</param>
  849. /// <param name="connection">todo: describe connection parameter on BuildIntCommand</param>
  850. /// <returns>SqlCommand 對象實例</returns>
  851. private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  852. {
  853. var command = BuildQueryCommand(connection, storedProcName, parameters);
  854. command.Parameters.Add(new SqlParameter("ReturnValue",
  855. SqlDbType.Int, 4, ParameterDirection.ReturnValue,
  856. false, 0, 0, string.Empty, DataRowVersion.Default, null));
  857. return command;
  858. }
  859. #endregion 存储過程操作
  860. }
  861. }