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.

951 lines
36 KiB

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