纽威
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.

828 lines
29 KiB

1 year ago
  1. using NFine.Code;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace NFine.Data.Extensions
  11. {
  12. /// <summary>
  13. /// 数据库访问辅助类,add by ngye, on 2013-08-14.
  14. /// </summary>
  15. public static class SqlHelper
  16. {
  17. #region [ 连接串相关 ]
  18. /// <summary>
  19. /// 数据中心DB的连接字符串
  20. /// </summary>
  21. public static string DataCenterConnString = ConfigurationManager.ConnectionStrings["WMSconnstr"].ConnectionString;
  22. /// <summary>
  23. /// 获取同步服务器的连接
  24. /// </summary>
  25. /// <returns></returns>
  26. public static SqlConnection GetDataCenterConn()
  27. {
  28. return new SqlConnection(DataCenterConnString);
  29. }
  30. /// <summary>
  31. /// 根据连接串获取连接
  32. /// </summary>
  33. /// <returns></returns>
  34. public static SqlConnection GetConnByStr(string connStr)
  35. {
  36. string ConnString = ConfigurationManager.ConnectionStrings[connStr].ConnectionString;
  37. return new SqlConnection(ConnString);
  38. }
  39. /// <summary>
  40. /// 根据连接串获取连接
  41. /// </summary>
  42. /// <returns></returns>
  43. public static SqlConnection GetConnByString(string conn)
  44. {
  45. return new SqlConnection(conn);
  46. }
  47. /// <summary>
  48. /// 测试连接串是否能正确
  49. /// </summary>
  50. /// <param name="connectionString">连接串</param>
  51. /// <returns></returns>
  52. public static bool TestConnectionString(string connectionString)
  53. {
  54. bool result = true;
  55. try
  56. {
  57. using (SqlConnection conn = GetConnByString(connectionString))
  58. {
  59. try
  60. {
  61. conn.Open();
  62. }
  63. catch (Exception ex)
  64. {
  65. result = false;
  66. }
  67. }
  68. }
  69. catch (Exception)
  70. {
  71. result = false;
  72. }
  73. return result;
  74. }
  75. /// <summary>
  76. /// 测试连接串是否正确
  77. /// </summary>
  78. /// <param name="connectionString">连接串</param>
  79. /// <param name="timeOut">测试的超时秒数</param>
  80. /// <param name="errInfo">错误时输出的错误信息</param>
  81. /// <returns>是否能正常连接</returns>
  82. public static bool TestConnectionString(string connectionString, int timeOut, ref string errInfo)
  83. {
  84. bool result = true;
  85. string[] arr = connectionString.Split(new char[] { ';' });
  86. List<string> list = new List<string>();
  87. foreach (string s in arr)
  88. {
  89. if (s.ToLower().IndexOf("timeout") == -1)
  90. {
  91. list.Add(s);
  92. }
  93. else
  94. {
  95. list.Add(String.Format("Connection Timeout={0}", timeOut));
  96. }
  97. }
  98. SqlConnection con = null;
  99. try
  100. {
  101. con = new SqlConnection(string.Join(";", list.ToArray()));
  102. con.Open();
  103. }
  104. catch (Exception ex)
  105. {
  106. result = false;
  107. errInfo = ex.Message;
  108. }
  109. finally
  110. {
  111. if (con != null)
  112. {
  113. con.Close();
  114. con.Dispose();
  115. con = null;
  116. }
  117. }
  118. return result;
  119. }
  120. #endregion
  121. #region [ 超时设置 ]
  122. public static int CommandTimeout
  123. {
  124. get
  125. {
  126. return 7200;
  127. }
  128. }
  129. #endregion
  130. #region [ ExecuteNonQuery ]
  131. /// <summary>
  132. /// 根据sql语句和参数,返回受影响行数
  133. /// </summary>
  134. /// <param name="sql">sql语句</param>
  135. /// <param name="spArr">可变参数</param>
  136. /// <returns>受影响行数</returns>
  137. public static int ExecuteNonQuery(string sql, params SqlParameter[] spArr)
  138. {
  139. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  140. {
  141. conn.Open();
  142. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  143. if (spArr.Length > 0)
  144. cmd.Parameters.AddRange(spArr.SetDBNull());
  145. return cmd.ExecuteNonQuery();
  146. }
  147. }
  148. public static int ExecuteNonQuery(string connStr,string sql, params SqlParameter[] spArr)
  149. {
  150. using (SqlConnection conn = new SqlConnection(connStr))
  151. {
  152. conn.Open();
  153. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  154. if (spArr.Length > 0)
  155. cmd.Parameters.AddRange(spArr.SetDBNull());
  156. return cmd.ExecuteNonQuery();
  157. }
  158. }
  159. #endregion
  160. #region [ ExecuteScalar_ForProc ]
  161. /// <summary>
  162. /// 根据存储过程和参数,返回Scalar结果
  163. /// </summary>
  164. /// <param name="proc">存储过程</param>
  165. /// <param name="spArr">可变参数</param>
  166. /// <returns>object</returns>
  167. public static object ExecuteScalar_ForProc(string proc, params SqlParameter[] spArr)
  168. {
  169. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  170. {
  171. conn.Open();
  172. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  173. cmd.CommandType = CommandType.StoredProcedure;
  174. if (spArr.Length > 0)
  175. cmd.Parameters.AddRange(spArr.SetDBNull());
  176. object obj = cmd.ExecuteScalar();
  177. return obj;
  178. }
  179. }
  180. /// <summary>
  181. /// 根据存储过程和参数,返回Scalar结果,但不加上超时设置 ( 避免循环做 AddTimeout )
  182. /// </summary>
  183. /// <param name="proc">存储过程</param>
  184. /// <param name="spArr">可变参数</param>
  185. /// <returns>object</returns>
  186. public static object ExecuteScalar_ForProc_WithoutAddTimeout(string proc, params SqlParameter[] spArr)
  187. {
  188. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  189. {
  190. conn.Open();
  191. SqlCommand cmd = new SqlCommand(proc, conn);
  192. cmd.CommandType = CommandType.StoredProcedure;
  193. if (spArr.Length > 0)
  194. cmd.Parameters.AddRange(spArr.SetDBNull());
  195. object obj = cmd.ExecuteScalar();
  196. return obj;
  197. }
  198. }
  199. #endregion
  200. #region [ ExecuteScalar ]
  201. /// <summary>
  202. /// 根据sql语句和参数,返回Scalar结果
  203. /// </summary>
  204. /// <param name="sql">sql语句</param>
  205. /// <param name="spArr">可变参数</param>
  206. /// <returns>object</returns>
  207. public static object ExecuteScalar(string sql, params SqlParameter[] spArr)
  208. {
  209. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  210. {
  211. conn.Open();
  212. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  213. if (spArr.Length > 0)
  214. cmd.Parameters.AddRange(spArr.SetDBNull());
  215. object obj = cmd.ExecuteScalar();
  216. return obj;
  217. }
  218. }
  219. #endregion
  220. #region [ QueryByProc ]
  221. /// <summary>
  222. /// 根据存储过程及参数,返回DataSet
  223. /// </summary>
  224. /// <returns>DataSet</returns>
  225. public static DataSet GetDataSetByProc(string proc, params SqlParameter[] spArr)
  226. {
  227. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  228. {
  229. conn.Open();
  230. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  231. cmd.CommandType = CommandType.StoredProcedure;
  232. if (spArr.Length > 0)
  233. cmd.Parameters.AddRange(spArr.SetDBNull());
  234. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  235. DataSet ds = new DataSet();
  236. adapter.Fill(ds);
  237. return ds;
  238. }
  239. }
  240. /// <summary>
  241. /// 根据存储过程及参数,返回DataTable
  242. /// </summary>
  243. /// <returns>DataTable</returns>
  244. public static DataTable GetDataTableByProc(string proc, params SqlParameter[] spArr)
  245. {
  246. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  247. {
  248. conn.Open();
  249. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  250. cmd.CommandType = CommandType.StoredProcedure;
  251. if (spArr.Length > 0)
  252. cmd.Parameters.AddRange(spArr.SetDBNull());
  253. DataTable dt = cmd.ExecuteDataTable();
  254. return dt;
  255. }
  256. }
  257. /// <summary>
  258. /// 根据sql语句和参数,返回DataRow
  259. /// </summary>
  260. /// <param name="sql">sql语句</param>
  261. /// <param name="spArr">可变参数</param>
  262. /// <returns>DataRow</returns>
  263. public static DataRow GetDataRowByProc(string proc, params SqlParameter[] spArr)
  264. {
  265. DataTable dt = GetDataTableByProc(proc, spArr);
  266. if (dt == null || dt.Rows.Count == 0)
  267. return null;
  268. return dt.Rows[0];
  269. }
  270. #endregion
  271. #region [ Query ]
  272. /// <summary>
  273. /// 根据sql语句和参数,返回DataSet
  274. /// </summary>
  275. /// <param name="sql">sql语句</param>
  276. /// <param name="spArr">可变参数</param>
  277. /// <returns>DataSet</returns>
  278. public static DataSet GetDataSetBySql(string sql, params SqlParameter[] spArr)
  279. {
  280. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  281. {
  282. conn.Open();
  283. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  284. if (spArr.Length > 0)
  285. cmd.Parameters.AddRange(spArr.SetDBNull());
  286. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  287. DataSet ds = new DataSet();
  288. adapter.Fill(ds);
  289. return ds;
  290. }
  291. }
  292. /// <summary>
  293. /// 根据sql语句和参数,返回DataTable
  294. /// </summary>
  295. /// <param name="sql">sql语句</param>
  296. /// <param name="spArr">可变参数</param>
  297. /// <returns>DataTable</returns>
  298. public static DataTable GetDataTableBySql(string sql, params SqlParameter[] spArr)
  299. {
  300. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  301. {
  302. conn.Open();
  303. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  304. if (spArr.Length > 0)
  305. cmd.Parameters.AddRange(spArr.SetDBNull());
  306. DataTable dt = cmd.ExecuteDataTable();
  307. return dt;
  308. }
  309. }
  310. /// <summary>
  311. /// 根据sql语句和参数,返回DataRow
  312. /// </summary>
  313. /// <param name="sql">sql语句</param>
  314. /// <param name="spArr">可变参数</param>
  315. /// <returns>DataRow</returns>
  316. public static DataRow GetDataRowBySql(string sql, params SqlParameter[] spArr)
  317. {
  318. DataTable dt = GetDataTableBySql(sql, spArr);
  319. if (dt == null || dt.Rows.Count == 0)
  320. return null;
  321. return dt.Rows[0];
  322. }
  323. /// <summary>
  324. /// 根据sql语句和参数,返回DataSet
  325. /// </summary>
  326. /// <param name="sql">sql语句</param>
  327. /// <param name="ConnectStr">数据库链接名称</param>
  328. /// <param name="spArr">可变参数</param>
  329. /// <returns>DataSet</returns>
  330. public static DataSet GetDataSetBySql_OtherConn(string sql, string ConnectStr, params SqlParameter[] spArr)
  331. {
  332. using (SqlConnection conn = SqlHelper.GetConnByStr(ConnectStr))
  333. {
  334. conn.Open();
  335. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  336. if (spArr.Length > 0)
  337. cmd.Parameters.AddRange(spArr.SetDBNull());
  338. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  339. DataSet ds = new DataSet();
  340. adapter.Fill(ds);
  341. return ds;
  342. }
  343. }
  344. /// <summary>
  345. /// 根据sql语句和参数,返回DataTable
  346. /// </summary>
  347. /// <param name="sql">sql语句</param>
  348. /// <param name="ConnectStr">数据库链接名称</param>
  349. /// <param name="spArr">可变参数</param>
  350. /// <returns>DataTable</returns>
  351. public static DataTable GetDataTableBySql_OtherConn(string sql, string ConnectStr, params SqlParameter[] spArr)
  352. {
  353. using (SqlConnection conn = SqlHelper.GetConnByStr(ConnectStr))
  354. {
  355. conn.Open();
  356. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  357. if (spArr != null && spArr.Length > 0)
  358. cmd.Parameters.AddRange(spArr.SetDBNull());
  359. DataTable dt = cmd.ExecuteDataTable();
  360. return dt;
  361. }
  362. }
  363. /// <summary>
  364. /// 根据sql语句和参数,返回DataTable 分页显示
  365. /// </summary>
  366. /// <param name="sql">sql语句</param>
  367. /// <param name="ConnectStr">数据库链接名称</param>
  368. /// <param name="spArr">可变参数</param>
  369. /// <returns>DataTable</returns>
  370. public static DataTable GetDataTableBySql_OtherConn(string sql, string ConnectStr, ref Pagination jqgridparam, params SqlParameter[] spArr)
  371. {
  372. using (SqlConnection conn = SqlHelper.GetConnByStr(ConnectStr))
  373. {
  374. string orderField = jqgridparam.sidx;
  375. string orderType = jqgridparam.sord;
  376. int pageIndex = jqgridparam.page;
  377. int pageSize = jqgridparam.rows;
  378. int totalRow = 0;
  379. string OrderBy = "";
  380. if (pageIndex == 0)
  381. {
  382. pageIndex = 1;
  383. }
  384. int num = (pageIndex - 1) * pageSize;
  385. int num1 = (pageIndex) * pageSize;
  386. if (!string.IsNullOrEmpty(orderField))
  387. OrderBy = orderField + " " + orderType + "";
  388. conn.Open();
  389. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  390. if (spArr != null && spArr.Length > 0)
  391. cmd.Parameters.AddRange(spArr.SetDBNull());
  392. DataTable dt = cmd.ExecuteDataTable();
  393. DataTable dtNew = dt.Clone();
  394. if (dt != null && dt.Rows.Count > 0)
  395. {
  396. jqgridparam.records = dt.Rows.Count;
  397. DataView dv = dt.DefaultView;
  398. dv.Sort = OrderBy;
  399. dt = dv.ToTable();
  400. if (dt.Rows.Count >= num)
  401. {
  402. for (int i = num; i < num1 && i < dt.Rows.Count; i++)
  403. {
  404. dtNew.ImportRow(dt.Rows[i]);
  405. }
  406. }
  407. }
  408. return dtNew;
  409. }
  410. }
  411. /// <summary>
  412. /// 根据sql语句和参数,返回DataRow
  413. /// </summary>
  414. /// <param name="sql">sql语句</param>
  415. /// <param name="ConnectStr">数据库链接名称</param>
  416. /// <param name="spArr">可变参数</param>
  417. /// <returns>DataRow</returns>
  418. public static DataRow GetDataRowBySql_OtherConn(string sql, string ConnectStr, params SqlParameter[] spArr)
  419. {
  420. DataTable dt = GetDataTableBySql_OtherConn(sql, ConnectStr, spArr);
  421. if (dt == null || dt.Rows.Count == 0)
  422. return null;
  423. return dt.Rows[0];
  424. }
  425. #endregion
  426. #region [ GetValue ]
  427. public static object GetValue(DataRow dr, string fieldName, object replaceValue)
  428. {
  429. if (dr.IsNull(fieldName))
  430. return replaceValue;
  431. return dr[fieldName];
  432. }
  433. public static object GetValue(DataRow dr, int idx, object replaceValue)
  434. {
  435. if (dr.IsNull(idx))
  436. return replaceValue;
  437. return dr[idx];
  438. }
  439. #endregion
  440. #region [ GetString ]
  441. public static string GetString(DataRow dr, string fieldName, string replaceValue)
  442. {
  443. if (dr.IsNull(fieldName))
  444. return replaceValue;
  445. return Convert.ToString(dr[fieldName]);
  446. }
  447. public static string GetString(DataRow dr, int idx, string replaceValue)
  448. {
  449. if (dr.IsNull(idx))
  450. return replaceValue;
  451. return Convert.ToString(dr[idx]);
  452. }
  453. #endregion
  454. #region [ GetDateTime ]
  455. public static DateTime GetDateTime(DataRow dr, string fieldName, DateTime replaceValue)
  456. {
  457. if (dr.IsNull(fieldName))
  458. return replaceValue;
  459. return Convert.ToDateTime(dr[fieldName]);
  460. }
  461. public static DateTime GetDateTime(DataRow dr, int idx, DateTime replaceValue)
  462. {
  463. if (dr.IsNull(idx))
  464. return replaceValue;
  465. return Convert.ToDateTime(dr[idx]);
  466. }
  467. #endregion
  468. #region [ 非数据中心库操作 ]
  469. #region [ ExecuteScalar ]
  470. /// <summary>
  471. /// 根据sql语句和参数,返回Scalar结果
  472. /// </summary>
  473. /// <param name="connString">连接串</param>
  474. /// <param name="sql">sql语句</param>
  475. /// <param name="spArr">可变参数</param>
  476. /// <returns>object</returns>
  477. public static object ExecuteScalarWithConn(string connString, string sql, params SqlParameter[] spArr)
  478. {
  479. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  480. {
  481. conn.Open();
  482. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  483. if (spArr.Length > 0)
  484. cmd.Parameters.AddRange(spArr.SetDBNull());
  485. object obj = cmd.ExecuteScalar();
  486. return obj;
  487. }
  488. }
  489. #endregion
  490. #region [ ExecuteNonQuery ]
  491. /// <summary>
  492. /// 根据sql语句和参数,返回受影响行数
  493. /// </summary>
  494. /// <param name="connString">连接串</param>
  495. /// <param name="sql">sql语句</param>
  496. /// <param name="spArr">可变参数</param>
  497. /// <returns>受影响行数</returns>
  498. public static int ExecuteNonQueryWithConn(string connString, string sql, params SqlParameter[] spArr)
  499. {
  500. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  501. {
  502. conn.Open();
  503. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  504. if (spArr.Length > 0)
  505. cmd.Parameters.AddRange(spArr.SetDBNull());
  506. return cmd.ExecuteNonQuery();
  507. }
  508. }
  509. #endregion
  510. #region [ Query ]
  511. /// <summary>
  512. /// 根据sql语句和参数,返回DataTable
  513. /// </summary>
  514. /// <param name="connString">连接串</param>
  515. /// <param name="sql">sql语句</param>
  516. /// <param name="spArr">可变参数</param>
  517. /// <returns>DataTable</returns>
  518. public static DataTable GetDataTableBySqlWithConn(string connString, string sql, params SqlParameter[] spArr)
  519. {
  520. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  521. {
  522. conn.Open();
  523. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  524. if (spArr.Length > 0)
  525. cmd.Parameters.AddRange(spArr.SetDBNull());
  526. DataTable dt = cmd.ExecuteDataTable();
  527. return dt;
  528. }
  529. }
  530. /// <summary>
  531. /// 根据sql语句和参数,返回DataRow
  532. /// </summary>
  533. /// <param name="connString">连接串</param>
  534. /// <param name="sql">sql语句</param>
  535. /// <param name="spArr">可变参数</param>
  536. /// <returns>DataRow</returns>
  537. public static DataRow GetDataRowBySqlWithConn(string connString, string sql, params SqlParameter[] spArr)
  538. {
  539. DataTable dt = GetDataTableBySqlWithConn(connString, sql, spArr);
  540. if (dt == null || dt.Rows.Count == 0)
  541. return null;
  542. return dt.Rows[0];
  543. }
  544. #endregion
  545. #endregion
  546. #region [ 根据SQL文件路径执行 ]
  547. /// <summary>
  548. /// 执行SQL文件
  549. /// </summary>
  550. /// <param name="connString"></param>
  551. /// <param name="filePath"></param>
  552. /// <returns></returns>
  553. public static bool ExecuteNonQueryWithConnAndSqlFilePath(string connString, string filePath)
  554. {
  555. string sql = System.IO.File.ReadAllText(filePath);
  556. return ExecuteNonQueryWithConnAndGO(connString, sql);
  557. }
  558. #endregion
  559. #region [ 执行带Go语句 ]
  560. /// <summary>
  561. /// 执行带"GO"的SQL,返回最后一条SQL的受影响行数
  562. /// </summary>
  563. /// <param name="connString">连接串</param>
  564. /// <param name="sql">sql语句</param>
  565. /// <returns>返回最后一条SQL的受影响行数</returns>
  566. public static bool ExecuteNonQueryWithConnAndGO(string connString, string sql)
  567. {
  568. bool result = true;
  569. string[] arr = System.Text.RegularExpressions.Regex.Split(sql, @"\bGO\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  570. using (SqlConnection conn = GetConnByString(connString))
  571. {
  572. conn.Open();
  573. SqlCommand cmd = new SqlCommand().AddTimeout();
  574. cmd.Connection = conn;
  575. SqlTransaction tx = conn.BeginTransaction();
  576. cmd.Transaction = tx;
  577. try
  578. {
  579. for (int n = 0; n < arr.Length; n++)
  580. {
  581. string strsql = arr[n];
  582. if (strsql.Trim().Length > 1 && strsql.Trim().Replace(";", "") != "")
  583. {
  584. cmd.CommandText = strsql;
  585. cmd.ExecuteNonQuery();
  586. }
  587. }
  588. tx.Commit();
  589. }
  590. catch (System.Data.SqlClient.SqlException E)
  591. {
  592. tx.Rollback();
  593. result = false;
  594. //return -1;
  595. throw new Exception(E.Message);
  596. }
  597. finally
  598. {
  599. if (conn.State != ConnectionState.Closed)
  600. {
  601. conn.Close();
  602. conn.Dispose();
  603. }
  604. }
  605. }
  606. return result;
  607. }
  608. #endregion
  609. /// <summary>
  610. /// 设置Sql参数
  611. /// </summary>
  612. /// <param name="parameterName"></param>
  613. /// <param name="value"></param>
  614. /// <param name="dbType"></param>
  615. /// <returns></returns>
  616. public static SqlParameter SetSqlParameter(string parameterName, object value, SqlDbType dbType)
  617. {
  618. if (value == null || string.IsNullOrEmpty(value.ToString()))
  619. {
  620. return new SqlParameter(parameterName, DBNull.Value);
  621. }
  622. SqlParameter sp = new SqlParameter(parameterName, value);
  623. sp.SqlDbType = dbType;
  624. return sp;
  625. }
  626. /// <summary>
  627. /// 根据sql及带 in 的id参数列表, 得到DataTable
  628. /// </summary>
  629. /// <param name="sql">带in ( {0} )的sql</param>
  630. /// <param name="ids">以逗号分隔的id字符串</param>
  631. /// <param name="idDbType">id的Sql数据类型</param>
  632. /// <returns>DataTable</returns>
  633. public static DataTable GetDataTableWithIn(string sql, string ids, SqlDbType idDbType)
  634. {
  635. SqlParameter[] spArr = GetWithInSqlParameters(ref sql, ids, idDbType);
  636. return GetDataTableBySql(sql, spArr);
  637. }
  638. /// <summary>
  639. /// 根据sql及带 in 的id参数列表, 得到受影响行数
  640. /// </summary>
  641. /// <param name="sql">带in ( {0} )的sql</param>
  642. /// <param name="ids">以逗号分隔的id字符串</param>
  643. /// <param name="idDbType">id的Sql数据类型</param>
  644. /// <returns>DataTable</returns>
  645. public static int ExecuteNonQueryWithIn(string sql, string ids, SqlDbType idDbType)
  646. {
  647. SqlParameter[] spArr = GetWithInSqlParameters(ref sql, ids, idDbType);
  648. return ExecuteNonQuery(sql, spArr);
  649. }
  650. #region [ 带 in 不确定参数的执行方法 ]
  651. /// <summary>
  652. /// 获取带 in 的sql参数列表
  653. /// </summary>
  654. /// <param name="sql">带in ( {0} )的sql</param>
  655. /// <param name="ids">以逗号分隔的id字符串</param>
  656. /// <param name="idDbType">id的Sql数据类型</param>
  657. /// <returns>sql参数列表</returns>
  658. public static SqlParameter[] GetWithInSqlParameters(ref string sql, string ids, SqlDbType idDbType)
  659. {
  660. if (string.IsNullOrEmpty(ids))
  661. {
  662. return null;
  663. }
  664. string[] idArr = ids.Split(',');
  665. //组建sql在in中的字符串
  666. StringBuilder sbCondition = new StringBuilder();
  667. List<SqlParameter> spList = new List<SqlParameter>();
  668. for (int i = 0; i < idArr.Length; i++)
  669. {
  670. string id = idArr[i];
  671. string spName = string.Format("@id{0}", i);
  672. sbCondition.AppendFormat("{0},", spName);
  673. spList.Add(SetSqlParameter(spName, id, idDbType));
  674. }
  675. //重新构建sql
  676. sql = string.Format(sql, sbCondition.ToString().TrimEnd(','));
  677. return spList.ToArray();
  678. }
  679. #endregion
  680. }//end of class
  681. #region [ SqlHelper 的扩展方法类 ]
  682. /// <summary>
  683. /// 扩展方法类
  684. /// </summary>
  685. public static class SqlHelperExtensionMethods
  686. {
  687. /// <summary>
  688. /// 新建SqlCommand对象时, 自动加上指定的 CommandTimeout. by ngye, on 2013-07-11.
  689. /// </summary>
  690. /// <param name="cmd">SqlCommand对象</param>
  691. /// <returns>SqlCommand对象</returns>
  692. public static SqlCommand AddTimeout(this SqlCommand cmd)
  693. {
  694. cmd.CommandTimeout = SqlHelper.CommandTimeout;
  695. return cmd;
  696. }
  697. /// <summary>
  698. /// 新建SqlBulkCopy对象时, 自动加上指定的 BulkCopyTimeout. by ngye, on 2013-08-30.
  699. /// </summary>
  700. /// <param name="cmd">SqlBulkCopy对象</param>
  701. /// <returns>SqlBulkCopy对象</returns>
  702. public static SqlBulkCopy AddTimeout(this SqlBulkCopy bulkCopy)
  703. {
  704. bulkCopy.BulkCopyTimeout = SqlHelper.CommandTimeout;
  705. return bulkCopy;
  706. }
  707. /// <summary>
  708. /// 执行cmd得到 DataTable. by ngye, on 2013-08-01
  709. /// </summary>
  710. /// <param name="cmd"></param>
  711. /// <returns></returns>
  712. public static DataTable ExecuteDataTable(this SqlCommand cmd)
  713. {
  714. DataTable dt = new DataTable();
  715. using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
  716. {
  717. adapter.Fill(dt);
  718. }
  719. return dt;
  720. }
  721. /// <summary>
  722. /// 为SqlParameter设置参数. by ngye, on 2013-08-15.
  723. /// </summary>
  724. /// <param name="sp"></param>
  725. /// <returns></returns>
  726. public static SqlParameter SetValue(this SqlParameter sp, object value)
  727. {
  728. sp.Value = value;
  729. return sp;
  730. }
  731. /// <summary>
  732. /// 为SqlParameter设置SqlDbType. by ngye, on 2013-09-03.
  733. /// </summary>
  734. /// <param name="sp"></param>
  735. /// <returns></returns>
  736. public static SqlParameter SetSqlDbType(this SqlParameter sp, SqlDbType dbType)
  737. {
  738. sp.SqlDbType = dbType;
  739. return sp;
  740. }
  741. /// <summary>
  742. /// 对可以为空的值作这样的处理,一旦其为空,就设置为DBNull.value.
  743. /// </summary>
  744. /// <param name="sp"></param>
  745. /// <returns></returns>
  746. public static SqlParameter[] SetDBNull(this SqlParameter[] spArr)
  747. {
  748. if (spArr == null || spArr.Length == 0)
  749. return spArr;
  750. for (int i = 0; i < spArr.Length; i++)
  751. {
  752. SqlParameter sp = spArr[i];
  753. if (sp.Value == null)
  754. sp.Value = DBNull.Value;
  755. }
  756. return spArr;
  757. }
  758. }
  759. #endregion
  760. }