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

1279 lines
45 KiB

3 years ago
2 years ago
3 years ago
  1. using ICS.Data;
  2. using NFine.Code;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace NFine.Data.Extensions
  14. {
  15. /// <summary>
  16. /// 数据库访问辅助类,add by ngye, on 2013-08-14.
  17. /// </summary>
  18. public static class SqlHelper
  19. {
  20. #region [ 连接串相关 ]
  21. /// <summary>
  22. /// 数据中心DB的连接字符串
  23. /// </summary>
  24. public static string DataCenterConnString = FromMd5(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
  25. public static void ExecuteDataSet(DataSet data)
  26. {
  27. try
  28. {
  29. //DBHelper.ExecuteNonQuery(dsconn, CommandType.Text, sql);
  30. using (SqlConnection destinationConnection = new SqlConnection(DataCenterConnString))
  31. {
  32. destinationConnection.Open();//打开连接
  33. SqlTransaction bulkTran = destinationConnection.BeginTransaction();
  34. using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection, SqlBulkCopyOptions.CheckConstraints, bulkTran))
  35. {
  36. //将DataTable插入到后台
  37. bulkCopy.BulkCopyTimeout = 30;
  38. foreach (DataTable dt in data.Tables)
  39. {
  40. bulkCopy.DestinationTableName = dt.TableName;//目标数据表名
  41. try
  42. {
  43. bulkCopy.WriteToServer(dt);
  44. }
  45. catch (Exception eBulk)
  46. {
  47. bulkTran.Rollback();
  48. bulkCopy.Close();
  49. destinationConnection.Close();
  50. throw eBulk;
  51. }
  52. }
  53. bulkTran.Commit();
  54. bulkCopy.Close();
  55. }
  56. destinationConnection.Close();
  57. }
  58. }
  59. catch (Exception ex)
  60. {
  61. throw ex;
  62. }
  63. }
  64. #region 字符串加解密
  65. /// <summary>
  66. /// MD5加密
  67. /// </summary>
  68. /// <param name="str"></param>
  69. /// <returns></returns>
  70. public static string ToMd5(string str)
  71. {
  72. return Encrypt(str, "&%#@?,:*_");
  73. }
  74. /// <summary>
  75. /// MD5解密
  76. /// </summary>
  77. /// <param name="str"></param>
  78. /// <returns></returns>
  79. public static string FromMd5(string str)
  80. {
  81. //return str;
  82. return Decrypt(str, "&%#@?,:*_");
  83. }
  84. /// <summary>
  85. /// 加密
  86. /// </summary>
  87. /// <param name="strText"></param>
  88. /// <param name="strEncrKey"></param>
  89. /// <returns></returns>
  90. private static String Encrypt(String strText, String strEncrKey)
  91. {
  92. Byte[] byKey = { };
  93. Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  94. try
  95. {
  96. byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
  97. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  98. Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
  99. MemoryStream ms = new MemoryStream();
  100. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV),
  101. CryptoStreamMode.Write);
  102. cs.Write(inputByteArray, 0, inputByteArray.Length);
  103. cs.FlushFinalBlock();
  104. return Convert.ToBase64String(ms.ToArray());
  105. }
  106. catch (Exception ex)
  107. {
  108. return ex.Message;
  109. }
  110. }
  111. /// <summary>
  112. /// 解密
  113. /// </summary>
  114. /// <param name="strText"></param>
  115. /// <param name="sDecrKey"></param>
  116. /// <returns></returns>
  117. private static String Decrypt(String strText, String sDecrKey)
  118. {
  119. Byte[] byKey = { };
  120. Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  121. Byte[] inputByteArray = new byte[strText.Length];
  122. try
  123. {
  124. byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
  125. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  126. inputByteArray = Convert.FromBase64String(strText);
  127. MemoryStream ms = new MemoryStream();
  128. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV),
  129. CryptoStreamMode.Write);
  130. cs.Write(inputByteArray, 0, inputByteArray.Length);
  131. cs.FlushFinalBlock();
  132. System.Text.Encoding encoding = System.Text.Encoding.UTF8;
  133. return encoding.GetString(ms.ToArray());
  134. }
  135. catch (Exception ex)
  136. {
  137. return ex.Message;
  138. }
  139. }
  140. #endregion
  141. /// <summary>
  142. /// 获取同步服务器的连接
  143. /// </summary>
  144. /// <returns></returns>
  145. public static SqlConnection GetDataCenterConn()
  146. {
  147. return new SqlConnection(DataCenterConnString);
  148. }
  149. /// <summary>
  150. /// 根据连接串获取连接
  151. /// </summary>
  152. /// <returns></returns>
  153. public static SqlConnection GetConnByStr(string connStr)
  154. {
  155. string ConnString = FromMd5( ConfigurationManager.ConnectionStrings[connStr].ConnectionString);
  156. return new SqlConnection(ConnString);
  157. }
  158. //public static SqlConnection SetDateBase(){
  159. // ConfigurationManager.ConnectionStrings["connstr"] = MD5DbTXT;
  160. // config.Save();
  161. // }
  162. /// <summary>
  163. /// 根据连接串获取连接
  164. /// </summary>
  165. /// <returns></returns>
  166. public static SqlConnection GetConnByString(string conn)
  167. {
  168. return new SqlConnection(conn);
  169. }
  170. /// <summary>
  171. /// 测试连接串是否能正确
  172. /// </summary>
  173. /// <param name="connectionString">连接串</param>
  174. /// <returns></returns>
  175. public static bool TestConnectionString(string connectionString)
  176. {
  177. bool result = true;
  178. try
  179. {
  180. using (SqlConnection conn = GetConnByString(connectionString))
  181. {
  182. try
  183. {
  184. conn.Open();
  185. }
  186. catch (Exception ex)
  187. {
  188. result = false;
  189. }
  190. }
  191. }
  192. catch (Exception)
  193. {
  194. result = false;
  195. }
  196. return result;
  197. }
  198. /// <summary>
  199. /// 测试连接串是否正确
  200. /// </summary>
  201. /// <param name="connectionString">连接串</param>
  202. /// <param name="timeOut">测试的超时秒数</param>
  203. /// <param name="errInfo">错误时输出的错误信息</param>
  204. /// <returns>是否能正常连接</returns>
  205. public static bool TestConnectionString(string connectionString, int timeOut, ref string errInfo)
  206. {
  207. bool result = true;
  208. string[] arr = connectionString.Split(new char[] { ';' });
  209. List<string> list = new List<string>();
  210. foreach (string s in arr)
  211. {
  212. if (s.ToLower().IndexOf("timeout") == -1)
  213. {
  214. list.Add(s);
  215. }
  216. else
  217. {
  218. list.Add(String.Format("Connection Timeout={0}", timeOut));
  219. }
  220. }
  221. SqlConnection con = null;
  222. try
  223. {
  224. con = new SqlConnection(string.Join(";", list.ToArray()));
  225. con.Open();
  226. }
  227. catch (Exception ex)
  228. {
  229. result = false;
  230. errInfo = ex.Message;
  231. }
  232. finally
  233. {
  234. if (con != null)
  235. {
  236. con.Close();
  237. con.Dispose();
  238. con = null;
  239. }
  240. }
  241. return result;
  242. }
  243. #endregion
  244. #region [ 超时设置 ]
  245. public static int CommandTimeout
  246. {
  247. get
  248. {
  249. return 7200;
  250. }
  251. }
  252. #endregion
  253. /// <summary>
  254. /// DataSet转Json字符串,主子结构
  255. /// 需要建立主子表关系,第一张表为主表
  256. /// 会排除关联列
  257. /// </summary>
  258. /// <param name="dataSet"></param>
  259. /// <param name="RelationName">关系名称</param>
  260. /// <returns></returns>
  261. public static string DataSetToJson(DataSet dataSet, string RelationName, string column)
  262. {
  263. DataRelation dataRelation = new DataRelation(RelationName, dataSet.Tables[0].Columns[column], dataSet.Tables[1].Columns[column]);
  264. dataSet.Relations.Add(dataRelation);
  265. StringBuilder jsonString = new StringBuilder();
  266. //foreach (DataTable table in dataSet.Tables)
  267. //{
  268. DataTable table = dataSet.Tables[0];
  269. jsonString.Append("[");
  270. DataRowCollection drc = table.Rows;
  271. for (int i = 0; i < drc.Count; i++)
  272. {
  273. DataRow dataRow = drc[i];
  274. jsonString.Append("{");
  275. for (int j = 0; j < table.Columns.Count; j++)
  276. {
  277. string strKey = table.Columns[j].ColumnName;
  278. if (dataSet.Relations[RelationName].ParentColumns.Select(a => a.Caption).Contains(strKey))
  279. continue;
  280. string strValue = dataRow[j].ToString();
  281. Type type = table.Columns[j].DataType;
  282. jsonString.Append("\"" + strKey + "\":");
  283. strValue = StringFormat(strValue, type);
  284. if (j < table.Columns.Count - 1)
  285. {
  286. jsonString.Append(strValue + ",");
  287. }
  288. else
  289. {
  290. jsonString.Append(strValue);
  291. }
  292. }
  293. jsonString.Append(",\"" + RelationName + "\":");
  294. DataRow[] drs = dataRow.GetChildRows(RelationName);
  295. jsonString.Append("[");
  296. foreach (DataRow dr in drs)
  297. {
  298. DataTable dt = dr.Table;
  299. jsonString.Append("{");
  300. for (int j = 0; j < dt.Columns.Count; j++)
  301. {
  302. string strKey = dt.Columns[j].ColumnName;
  303. if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
  304. continue;
  305. string strValue = dr[j].ToString();
  306. Type type = dt.Columns[j].DataType;
  307. jsonString.Append("\"" + strKey + "\":");
  308. strValue = StringFormat(strValue, type);
  309. if (j < dt.Columns.Count - 1)
  310. {
  311. jsonString.Append(strValue + ",");
  312. }
  313. else
  314. {
  315. jsonString.Append(strValue);
  316. }
  317. }
  318. jsonString.Append("},");
  319. }
  320. if (drs.Length > 0)
  321. jsonString.Remove(jsonString.Length - 1, 1);
  322. jsonString.Append("]");
  323. jsonString.Append("},");
  324. }
  325. jsonString.Remove(jsonString.Length - 1, 1);
  326. jsonString.Append("]");
  327. //}
  328. string res = jsonString.ToString();
  329. return res;
  330. }
  331. /// <summary>
  332. /// 过滤特殊字符
  333. /// </summary>
  334. /// <param name="s">字符串</param>
  335. /// <returns>json字符串</returns>
  336. private static string String2Json(String s)
  337. {
  338. StringBuilder sb = new StringBuilder();
  339. for (int i = 0; i < s.Length; i++)
  340. {
  341. char c = s.ToCharArray()[i];
  342. switch (c)
  343. {
  344. case '\"':
  345. sb.Append("\\\""); break;
  346. case '\\':
  347. sb.Append("\\\\"); break;
  348. case '/':
  349. sb.Append("\\/"); break;
  350. case '\b':
  351. sb.Append("\\b"); break;
  352. case '\f':
  353. sb.Append("\\f"); break;
  354. case '\n':
  355. sb.Append("\\n"); break;
  356. case '\r':
  357. sb.Append("\\r"); break;
  358. case '\t':
  359. sb.Append("\\t"); break;
  360. default:
  361. sb.Append(c); break;
  362. }
  363. }
  364. return sb.ToString();
  365. }
  366. /// <summary>
  367. /// 格式化字符型、日期型、布尔型
  368. /// </summary>
  369. /// <param name="str"></param>
  370. /// <param name="type"></param>
  371. /// <returns></returns>
  372. private static string StringFormat(string str, Type type)
  373. {
  374. if (type == typeof(string))
  375. {
  376. str = String2Json(str);
  377. str = "\"" + str + "\"";
  378. }
  379. else if (type == typeof(DateTime))
  380. {
  381. str = "\"" + str + "\"";
  382. }
  383. else if (type == typeof(bool))
  384. {
  385. str = str.ToLower();
  386. }
  387. else if (type != typeof(string) && string.IsNullOrEmpty(str))
  388. {
  389. str = "\"" + str + "\"";
  390. }
  391. return str;
  392. }
  393. #region [ ExecuteNonQuery ]
  394. /// <summary>
  395. /// 根据sql语句和参数,返回受影响行数
  396. /// </summary>
  397. /// <param name="sql">sql语句</param>
  398. /// <param name="spArr">可变参数</param>
  399. /// <returns>受影响行数</returns>
  400. public static int ExecuteNonQuery(string sql, params SqlParameter[] spArr)
  401. {
  402. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  403. {
  404. conn.Open();
  405. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  406. if (spArr.Length > 0)
  407. cmd.Parameters.AddRange(spArr.SetDBNull());
  408. return cmd.ExecuteNonQuery();
  409. }
  410. }
  411. public static DataTable CmdExecuteDataTable(string sql)
  412. {
  413. try
  414. {
  415. string connString = SqlHelper.DataCenterConnString;
  416. SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
  417. conn.Open();
  418. SqlTransaction sqlTran = conn.BeginTransaction();
  419. SqlCommand cmd = new SqlCommand();
  420. cmd.Transaction = sqlTran;
  421. cmd.Connection = conn;
  422. try
  423. {
  424. DataTable dt = SqlCommandHelper.SQlReturnData(sql, cmd);
  425. cmd.Transaction.Commit();
  426. return dt;
  427. }
  428. catch (Exception ex)
  429. {
  430. cmd.Transaction.Rollback();
  431. throw new Exception(ex.Message);
  432. }
  433. finally
  434. {
  435. if (conn.State == ConnectionState.Open)
  436. {
  437. conn.Close();
  438. }
  439. conn.Dispose();
  440. }
  441. }
  442. catch (Exception ex)
  443. {
  444. throw new Exception(ex.Message);
  445. }
  446. }
  447. //多语句一起事务中执行(Li编写)
  448. public static int CmdExecuteNonQueryLi(string sql, params SqlParameter[] spArr)
  449. {
  450. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  451. {
  452. conn.Open();
  453. SqlTransaction sqlTran = conn.BeginTransaction();
  454. SqlCommand cmd = new SqlCommand();
  455. cmd.Transaction = sqlTran;
  456. cmd.Connection = conn;
  457. try
  458. {
  459. cmd.CommandText = sql;
  460. int RES = cmd.ExecuteNonQuery();
  461. cmd.Transaction.Commit();
  462. return RES;
  463. }
  464. catch (Exception ex)
  465. {
  466. cmd.Transaction.Rollback();
  467. throw new Exception(ex.Message);
  468. }
  469. finally
  470. {
  471. if (conn.State != ConnectionState.Closed)
  472. {
  473. conn.Close();
  474. conn.Dispose();
  475. }
  476. }
  477. return 0;
  478. }
  479. }
  480. public static int CmdExecuteNonQuery(string sql, params SqlParameter[] spArr)
  481. {
  482. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  483. {
  484. conn.Open();
  485. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  486. SqlTransaction tx = conn.BeginTransaction();
  487. cmd.Transaction = tx;
  488. try
  489. {
  490. int RES= cmd.ExecuteNonQuery();
  491. tx.Commit();
  492. return RES;
  493. }
  494. catch (System.Data.SqlClient.SqlException E)
  495. {
  496. tx.Rollback();
  497. throw new Exception(E.Message);
  498. }
  499. finally
  500. {
  501. if (conn.State != ConnectionState.Closed)
  502. {
  503. conn.Close();
  504. conn.Dispose();
  505. }
  506. }
  507. return 0;
  508. }
  509. }
  510. public static int ExecuteNonQuery(string connStr,string sql, params SqlParameter[] spArr)
  511. {
  512. using (SqlConnection conn = new SqlConnection(connStr))
  513. {
  514. conn.Open();
  515. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  516. if (spArr.Length > 0)
  517. cmd.Parameters.AddRange(spArr.SetDBNull());
  518. return cmd.ExecuteNonQuery();
  519. }
  520. }
  521. #endregion
  522. #region [ ExecuteScalar_ForProc ]
  523. /// <summary>
  524. /// 根据存储过程和参数,返回Scalar结果
  525. /// </summary>
  526. /// <param name="proc">存储过程</param>
  527. /// <param name="spArr">可变参数</param>
  528. /// <returns>object</returns>
  529. public static object ExecuteScalar_ForProc(string proc, params SqlParameter[] spArr)
  530. {
  531. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  532. {
  533. conn.Open();
  534. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  535. cmd.CommandType = CommandType.StoredProcedure;
  536. if (spArr.Length > 0)
  537. cmd.Parameters.AddRange(spArr.SetDBNull());
  538. object obj = cmd.ExecuteScalar();
  539. return obj;
  540. }
  541. }
  542. /// <summary>
  543. /// 根据存储过程和参数,返回Scalar结果,但不加上超时设置 ( 避免循环做 AddTimeout )
  544. /// </summary>
  545. /// <param name="proc">存储过程</param>
  546. /// <param name="spArr">可变参数</param>
  547. /// <returns>object</returns>
  548. public static object ExecuteScalar_ForProc_WithoutAddTimeout(string proc, params SqlParameter[] spArr)
  549. {
  550. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  551. {
  552. conn.Open();
  553. SqlCommand cmd = new SqlCommand(proc, conn);
  554. cmd.CommandType = CommandType.StoredProcedure;
  555. if (spArr.Length > 0)
  556. cmd.Parameters.AddRange(spArr.SetDBNull());
  557. object obj = cmd.ExecuteScalar();
  558. return obj;
  559. }
  560. }
  561. #endregion
  562. #region [ ExecuteScalar ]
  563. /// <summary>
  564. /// 根据sql语句和参数,返回Scalar结果
  565. /// </summary>
  566. /// <param name="sql">sql语句</param>
  567. /// <param name="spArr">可变参数</param>
  568. /// <returns>object</returns>
  569. public static object ExecuteScalar(string sql, params SqlParameter[] spArr)
  570. {
  571. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  572. {
  573. conn.Open();
  574. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  575. if (spArr.Length > 0)
  576. cmd.Parameters.AddRange(spArr.SetDBNull());
  577. object obj = cmd.ExecuteScalar();
  578. return obj;
  579. }
  580. }
  581. #endregion
  582. #region [ QueryByProc ]
  583. /// <summary>
  584. /// 根据存储过程及参数,返回DataSet
  585. /// </summary>
  586. /// <returns>DataSet</returns>
  587. public static DataSet GetDataSetByProc(string proc, params SqlParameter[] spArr)
  588. {
  589. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  590. {
  591. conn.Open();
  592. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  593. cmd.CommandType = CommandType.StoredProcedure;
  594. if (spArr.Length > 0)
  595. cmd.Parameters.AddRange(spArr.SetDBNull());
  596. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  597. DataSet ds = new DataSet();
  598. adapter.Fill(ds);
  599. return ds;
  600. }
  601. }
  602. /// <summary>
  603. /// 根据存储过程及参数,返回DataTable
  604. /// </summary>
  605. /// <returns>DataTable</returns>
  606. public static DataTable GetDataTableByProc(string proc, params SqlParameter[] spArr)
  607. {
  608. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  609. {
  610. conn.Open();
  611. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  612. cmd.CommandType = CommandType.StoredProcedure;
  613. if (spArr.Length > 0)
  614. cmd.Parameters.AddRange(spArr.SetDBNull());
  615. DataTable dt = cmd.ExecuteDataTable();
  616. return dt;
  617. }
  618. }
  619. /// <summary>
  620. /// 根据sql语句和参数,返回DataRow
  621. /// </summary>
  622. /// <param name="sql">sql语句</param>
  623. /// <param name="spArr">可变参数</param>
  624. /// <returns>DataRow</returns>
  625. public static DataRow GetDataRowByProc(string proc, params SqlParameter[] spArr)
  626. {
  627. DataTable dt = GetDataTableByProc(proc, spArr);
  628. if (dt == null || dt.Rows.Count == 0)
  629. return null;
  630. return dt.Rows[0];
  631. }
  632. #endregion
  633. #region [ Query ]
  634. /// <summary>
  635. /// 根据sql语句和参数,返回DataSet
  636. /// </summary>
  637. /// <param name="sql">sql语句</param>
  638. /// <param name="spArr">可变参数</param>
  639. /// <returns>DataSet</returns>
  640. public static DataSet GetDataSetBySql(string sql, params SqlParameter[] spArr)
  641. {
  642. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  643. {
  644. conn.Open();
  645. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  646. if (spArr.Length > 0)
  647. cmd.Parameters.AddRange(spArr.SetDBNull());
  648. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  649. DataSet ds = new DataSet();
  650. adapter.Fill(ds);
  651. return ds;
  652. }
  653. }
  654. /// <summary>
  655. /// 根据sql语句和参数,返回DataTable
  656. /// </summary>
  657. /// <param name="sql">sql语句</param>
  658. /// <param name="spArr">可变参数</param>
  659. /// <returns>DataTable</returns>
  660. public static DataTable GetDataTableBySql(string sql, params SqlParameter[] spArr)
  661. {
  662. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  663. {
  664. conn.Open();
  665. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  666. if (spArr.Length > 0)
  667. cmd.Parameters.AddRange(spArr.SetDBNull());
  668. DataTable dt = cmd.ExecuteDataTable();
  669. return dt;
  670. }
  671. }
  672. /// <summary>
  673. /// 根据sql语句和参数,返回DataRow
  674. /// </summary>
  675. /// <param name="sql">sql语句</param>
  676. /// <param name="spArr">可变参数</param>
  677. /// <returns>DataRow</returns>
  678. public static DataRow GetDataRowBySql(string sql, params SqlParameter[] spArr)
  679. {
  680. DataTable dt = GetDataTableBySql(sql, spArr);
  681. if (dt == null || dt.Rows.Count == 0)
  682. return null;
  683. return dt.Rows[0];
  684. }
  685. /// <summary>
  686. /// 根据sql语句和参数,返回DataSet
  687. /// </summary>
  688. /// <param name="sql">sql语句</param>
  689. /// <param name="ConnectStr">数据库链接名称</param>
  690. /// <param name="spArr">可变参数</param>
  691. /// <returns>DataSet</returns>
  692. public static DataSet GetDataSetBySql_OtherConn(string sql, string ConnectStr, params SqlParameter[] spArr)
  693. {
  694. using (SqlConnection conn = SqlHelper.GetConnByStr(ConnectStr))
  695. {
  696. conn.Open();
  697. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  698. if (spArr.Length > 0)
  699. cmd.Parameters.AddRange(spArr.SetDBNull());
  700. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  701. DataSet ds = new DataSet();
  702. adapter.Fill(ds);
  703. return ds;
  704. }
  705. }
  706. /// <summary>
  707. /// 根据sql语句和参数,返回DataTable
  708. /// </summary>
  709. /// <param name="sql">sql语句</param>
  710. /// <param name="ConnectStr">数据库链接名称</param>
  711. /// <param name="spArr">可变参数</param>
  712. /// <returns>DataTable</returns>
  713. public static DataTable GetDataTableBySql_OtherConn(string sql, string ConnectStr, params SqlParameter[] spArr)
  714. {
  715. using (SqlConnection conn = SqlHelper.GetConnByStr(ConnectStr))
  716. {
  717. conn.Open();
  718. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  719. if (spArr != null && spArr.Length > 0)
  720. cmd.Parameters.AddRange(spArr.SetDBNull());
  721. DataTable dt = cmd.ExecuteDataTable();
  722. return dt;
  723. }
  724. }
  725. /// <summary>
  726. /// 根据sql语句和参数,返回DataTable 分页显示
  727. /// </summary>
  728. /// <param name="sql">sql语句</param>
  729. /// <param name="ConnectStr">数据库链接名称</param>
  730. /// <param name="spArr">可变参数</param>
  731. /// <returns>DataTable</returns>
  732. public static DataTable GetDataTableBySql_OtherConn(string sql, string ConnectStr, ref Pagination jqgridparam, params SqlParameter[] spArr)
  733. {
  734. using (SqlConnection conn = SqlHelper.GetConnByStr(ConnectStr))
  735. {
  736. string orderField = jqgridparam.sidx;
  737. string orderType = jqgridparam.sord;
  738. int pageIndex = jqgridparam.page;
  739. int pageSize = jqgridparam.rows;
  740. int totalRow = 0;
  741. string OrderBy = "";
  742. if (pageIndex == 0)
  743. {
  744. pageIndex = 1;
  745. }
  746. int num = (pageIndex - 1) * pageSize;
  747. int num1 = (pageIndex) * pageSize;
  748. if (!string.IsNullOrEmpty(orderField))
  749. OrderBy = orderField + " " + orderType + "";
  750. conn.Open();
  751. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  752. if (spArr != null && spArr.Length > 0)
  753. cmd.Parameters.AddRange(spArr.SetDBNull());
  754. DataTable dt = cmd.ExecuteDataTable();
  755. DataTable dtNew = dt.Clone();
  756. if (dt != null && dt.Rows.Count > 0)
  757. {
  758. jqgridparam.records = dt.Rows.Count;
  759. DataView dv = dt.DefaultView;
  760. dv.Sort = OrderBy;
  761. dt = dv.ToTable();
  762. if (dt.Rows.Count >= num)
  763. {
  764. for (int i = num; i < num1 && i < dt.Rows.Count; i++)
  765. {
  766. dtNew.ImportRow(dt.Rows[i]);
  767. }
  768. }
  769. }
  770. return dtNew;
  771. }
  772. }
  773. /// <summary>
  774. /// 根据sql语句和参数,返回DataRow
  775. /// </summary>
  776. /// <param name="sql">sql语句</param>
  777. /// <param name="ConnectStr">数据库链接名称</param>
  778. /// <param name="spArr">可变参数</param>
  779. /// <returns>DataRow</returns>
  780. public static DataRow GetDataRowBySql_OtherConn(string sql, string ConnectStr, params SqlParameter[] spArr)
  781. {
  782. DataTable dt = GetDataTableBySql_OtherConn(sql, ConnectStr, spArr);
  783. if (dt == null || dt.Rows.Count == 0)
  784. return null;
  785. return dt.Rows[0];
  786. }
  787. #endregion
  788. #region [ GetValue ]
  789. public static object GetValue(DataRow dr, string fieldName, object replaceValue)
  790. {
  791. if (dr.IsNull(fieldName))
  792. return replaceValue;
  793. return dr[fieldName];
  794. }
  795. public static object GetValue(DataRow dr, int idx, object replaceValue)
  796. {
  797. if (dr.IsNull(idx))
  798. return replaceValue;
  799. return dr[idx];
  800. }
  801. #endregion
  802. #region [ GetString ]
  803. public static string GetString(DataRow dr, string fieldName, string replaceValue)
  804. {
  805. if (dr.IsNull(fieldName))
  806. return replaceValue;
  807. return Convert.ToString(dr[fieldName]);
  808. }
  809. public static string GetString(DataRow dr, int idx, string replaceValue)
  810. {
  811. if (dr.IsNull(idx))
  812. return replaceValue;
  813. return Convert.ToString(dr[idx]);
  814. }
  815. #endregion
  816. #region [ GetDateTime ]
  817. public static DateTime GetDateTime(DataRow dr, string fieldName, DateTime replaceValue)
  818. {
  819. if (dr.IsNull(fieldName))
  820. return replaceValue;
  821. return Convert.ToDateTime(dr[fieldName]);
  822. }
  823. public static DateTime GetDateTime(DataRow dr, int idx, DateTime replaceValue)
  824. {
  825. if (dr.IsNull(idx))
  826. return replaceValue;
  827. return Convert.ToDateTime(dr[idx]);
  828. }
  829. #endregion
  830. #region [ 非数据中心库操作 ]
  831. #region [ ExecuteScalar ]
  832. /// <summary>
  833. /// 根据sql语句和参数,返回Scalar结果
  834. /// </summary>
  835. /// <param name="connString">连接串</param>
  836. /// <param name="sql">sql语句</param>
  837. /// <param name="spArr">可变参数</param>
  838. /// <returns>object</returns>
  839. public static object ExecuteScalarWithConn(string connString, string sql, params SqlParameter[] spArr)
  840. {
  841. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  842. {
  843. conn.Open();
  844. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  845. if (spArr.Length > 0)
  846. cmd.Parameters.AddRange(spArr.SetDBNull());
  847. object obj = cmd.ExecuteScalar();
  848. return obj;
  849. }
  850. }
  851. #endregion
  852. #region [ ExecuteNonQuery ]
  853. /// <summary>
  854. /// 根据sql语句和参数,返回受影响行数
  855. /// </summary>
  856. /// <param name="connString">连接串</param>
  857. /// <param name="sql">sql语句</param>
  858. /// <param name="spArr">可变参数</param>
  859. /// <returns>受影响行数</returns>
  860. public static int ExecuteNonQueryWithConn(string connString, string sql, params SqlParameter[] spArr)
  861. {
  862. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  863. {
  864. conn.Open();
  865. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  866. if (spArr.Length > 0)
  867. cmd.Parameters.AddRange(spArr.SetDBNull());
  868. return cmd.ExecuteNonQuery();
  869. }
  870. }
  871. #endregion
  872. #region [ Query ]
  873. /// <summary>
  874. /// 根据sql语句和参数,返回DataTable
  875. /// </summary>
  876. /// <param name="connString">连接串</param>
  877. /// <param name="sql">sql语句</param>
  878. /// <param name="spArr">可变参数</param>
  879. /// <returns>DataTable</returns>
  880. public static DataTable GetDataTableBySqlWithConn(string connString, string sql, params SqlParameter[] spArr)
  881. {
  882. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  883. {
  884. conn.Open();
  885. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  886. if (spArr.Length > 0)
  887. cmd.Parameters.AddRange(spArr.SetDBNull());
  888. DataTable dt = cmd.ExecuteDataTable();
  889. return dt;
  890. }
  891. }
  892. /// <summary>
  893. /// 根据sql语句和参数,返回DataRow
  894. /// </summary>
  895. /// <param name="connString">连接串</param>
  896. /// <param name="sql">sql语句</param>
  897. /// <param name="spArr">可变参数</param>
  898. /// <returns>DataRow</returns>
  899. public static DataRow GetDataRowBySqlWithConn(string connString, string sql, params SqlParameter[] spArr)
  900. {
  901. DataTable dt = GetDataTableBySqlWithConn(connString, sql, spArr);
  902. if (dt == null || dt.Rows.Count == 0)
  903. return null;
  904. return dt.Rows[0];
  905. }
  906. #endregion
  907. #endregion
  908. #region [ 根据SQL文件路径执行 ]
  909. /// <summary>
  910. /// 执行SQL文件
  911. /// </summary>
  912. /// <param name="connString"></param>
  913. /// <param name="filePath"></param>
  914. /// <returns></returns>
  915. public static bool ExecuteNonQueryWithConnAndSqlFilePath(string connString, string filePath)
  916. {
  917. string sql = System.IO.File.ReadAllText(filePath);
  918. return ExecuteNonQueryWithConnAndGO(connString, sql);
  919. }
  920. #endregion
  921. #region [ 执行带Go语句 ]
  922. /// <summary>
  923. /// 执行带"GO"的SQL,返回最后一条SQL的受影响行数
  924. /// </summary>
  925. /// <param name="connString">连接串</param>
  926. /// <param name="sql">sql语句</param>
  927. /// <returns>返回最后一条SQL的受影响行数</returns>
  928. public static bool ExecuteNonQueryWithConnAndGO(string connString, string sql)
  929. {
  930. bool result = true;
  931. string[] arr = System.Text.RegularExpressions.Regex.Split(sql, @"\bGO\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  932. using (SqlConnection conn = GetConnByString(connString))
  933. {
  934. conn.Open();
  935. SqlCommand cmd = new SqlCommand().AddTimeout();
  936. cmd.Connection = conn;
  937. SqlTransaction tx = conn.BeginTransaction();
  938. cmd.Transaction = tx;
  939. try
  940. {
  941. for (int n = 0; n < arr.Length; n++)
  942. {
  943. string strsql = arr[n];
  944. if (strsql.Trim().Length > 1 && strsql.Trim().Replace(";", "") != "")
  945. {
  946. cmd.CommandText = strsql;
  947. cmd.ExecuteNonQuery();
  948. }
  949. }
  950. tx.Commit();
  951. }
  952. catch (System.Data.SqlClient.SqlException E)
  953. {
  954. tx.Rollback();
  955. result = false;
  956. //return -1;
  957. throw new Exception(E.Message);
  958. }
  959. finally
  960. {
  961. if (conn.State != ConnectionState.Closed)
  962. {
  963. conn.Close();
  964. conn.Dispose();
  965. }
  966. }
  967. }
  968. return result;
  969. }
  970. #endregion
  971. /// <summary>
  972. /// 设置Sql参数
  973. /// </summary>
  974. /// <param name="parameterName"></param>
  975. /// <param name="value"></param>
  976. /// <param name="dbType"></param>
  977. /// <returns></returns>
  978. public static SqlParameter SetSqlParameter(string parameterName, object value, SqlDbType dbType)
  979. {
  980. if (value == null || string.IsNullOrEmpty(value.ToString()))
  981. {
  982. return new SqlParameter(parameterName, DBNull.Value);
  983. }
  984. SqlParameter sp = new SqlParameter(parameterName, value);
  985. sp.SqlDbType = dbType;
  986. return sp;
  987. }
  988. public static void RemoveEmpty(DataTable dt)
  989. {
  990. List<DataRow> removelist = new List<DataRow>();
  991. for (int i = 0; i < dt.Rows.Count; i++)
  992. {
  993. bool IsNull = true;
  994. for (int j = 0; j < dt.Columns.Count; j++)
  995. {
  996. if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
  997. {
  998. IsNull = false;
  999. }
  1000. }
  1001. if (IsNull)
  1002. {
  1003. removelist.Add(dt.Rows[i]);
  1004. }
  1005. }
  1006. for (int i = 0; i < removelist.Count; i++)
  1007. {
  1008. dt.Rows.Remove(removelist[i]);
  1009. }
  1010. }
  1011. /// <summary>
  1012. /// 大数据插入
  1013. /// </summary>
  1014. /// <param name="connectionString">目标库连接</param>
  1015. /// <param name="TableName">目标表</param>
  1016. /// <param name="dtSelect">来源数据</param>
  1017. public static void SqlBulkCopyByDatatable( string TableName, DataTable dtSelect)
  1018. {
  1019. using (SqlConnection conn = new SqlConnection(DataCenterConnString))
  1020. {
  1021. using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(DataCenterConnString, SqlBulkCopyOptions.UseInternalTransaction))
  1022. {
  1023. try
  1024. {
  1025. sqlbulkcopy.DestinationTableName = TableName;
  1026. sqlbulkcopy.BatchSize = 20000;
  1027. sqlbulkcopy.BulkCopyTimeout = 0;//不限时间
  1028. for (int i = 0; i < dtSelect.Columns.Count; i++)
  1029. {
  1030. sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName);
  1031. }
  1032. sqlbulkcopy.WriteToServer(dtSelect);
  1033. }
  1034. catch (System.Exception ex)
  1035. {
  1036. throw ex;
  1037. }
  1038. }
  1039. }
  1040. }
  1041. /// <summary>
  1042. /// 根据sql及带 in 的id参数列表, 得到DataTable
  1043. /// </summary>
  1044. /// <param name="sql">带in ( {0} )的sql</param>
  1045. /// <param name="ids">以逗号分隔的id字符串</param>
  1046. /// <param name="idDbType">id的Sql数据类型</param>
  1047. /// <returns>DataTable</returns>
  1048. public static DataTable GetDataTableWithIn(string sql, string ids, SqlDbType idDbType)
  1049. {
  1050. SqlParameter[] spArr = GetWithInSqlParameters(ref sql, ids, idDbType);
  1051. return GetDataTableBySql(sql, spArr);
  1052. }
  1053. /// <summary>
  1054. /// 根据sql及带 in 的id参数列表, 得到受影响行数
  1055. /// </summary>
  1056. /// <param name="sql">带in ( {0} )的sql</param>
  1057. /// <param name="ids">以逗号分隔的id字符串</param>
  1058. /// <param name="idDbType">id的Sql数据类型</param>
  1059. /// <returns>DataTable</returns>
  1060. public static int ExecuteNonQueryWithIn(string sql, string ids, SqlDbType idDbType)
  1061. {
  1062. SqlParameter[] spArr = GetWithInSqlParameters(ref sql, ids, idDbType);
  1063. return ExecuteNonQuery(sql, spArr);
  1064. }
  1065. #region [ 带 in 不确定参数的执行方法 ]
  1066. /// <summary>
  1067. /// 获取带 in 的sql参数列表
  1068. /// </summary>
  1069. /// <param name="sql">带in ( {0} )的sql</param>
  1070. /// <param name="ids">以逗号分隔的id字符串</param>
  1071. /// <param name="idDbType">id的Sql数据类型</param>
  1072. /// <returns>sql参数列表</returns>
  1073. public static SqlParameter[] GetWithInSqlParameters(ref string sql, string ids, SqlDbType idDbType)
  1074. {
  1075. if (string.IsNullOrEmpty(ids))
  1076. {
  1077. return null;
  1078. }
  1079. string[] idArr = ids.Split(',');
  1080. //组建sql在in中的字符串
  1081. StringBuilder sbCondition = new StringBuilder();
  1082. List<SqlParameter> spList = new List<SqlParameter>();
  1083. for (int i = 0; i < idArr.Length; i++)
  1084. {
  1085. string id = idArr[i];
  1086. string spName = string.Format("@id{0}", i);
  1087. sbCondition.AppendFormat("{0},", spName);
  1088. spList.Add(SetSqlParameter(spName, id, idDbType));
  1089. }
  1090. //重新构建sql
  1091. sql = string.Format(sql, sbCondition.ToString().TrimEnd(','));
  1092. return spList.ToArray();
  1093. }
  1094. #endregion
  1095. }//end of class
  1096. #region [ SqlHelper 的扩展方法类 ]
  1097. /// <summary>
  1098. /// 扩展方法类
  1099. /// </summary>
  1100. public static class SqlHelperExtensionMethods
  1101. {
  1102. /// <summary>
  1103. /// 新建SqlCommand对象时, 自动加上指定的 CommandTimeout. by ngye, on 2013-07-11.
  1104. /// </summary>
  1105. /// <param name="cmd">SqlCommand对象</param>
  1106. /// <returns>SqlCommand对象</returns>
  1107. public static SqlCommand AddTimeout(this SqlCommand cmd)
  1108. {
  1109. cmd.CommandTimeout = SqlHelper.CommandTimeout;
  1110. return cmd;
  1111. }
  1112. /// <summary>
  1113. /// 新建SqlBulkCopy对象时, 自动加上指定的 BulkCopyTimeout. by ngye, on 2013-08-30.
  1114. /// </summary>
  1115. /// <param name="cmd">SqlBulkCopy对象</param>
  1116. /// <returns>SqlBulkCopy对象</returns>
  1117. public static SqlBulkCopy AddTimeout(this SqlBulkCopy bulkCopy)
  1118. {
  1119. bulkCopy.BulkCopyTimeout = SqlHelper.CommandTimeout;
  1120. return bulkCopy;
  1121. }
  1122. /// <summary>
  1123. /// 执行cmd得到 DataTable. by ngye, on 2013-08-01
  1124. /// </summary>
  1125. /// <param name="cmd"></param>
  1126. /// <returns></returns>
  1127. public static DataTable ExecuteDataTable(this SqlCommand cmd)
  1128. {
  1129. DataTable dt = new DataTable();
  1130. using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
  1131. {
  1132. adapter.Fill(dt);
  1133. }
  1134. return dt;
  1135. }
  1136. /// <summary>
  1137. /// 为SqlParameter设置参数. by ngye, on 2013-08-15.
  1138. /// </summary>
  1139. /// <param name="sp"></param>
  1140. /// <returns></returns>
  1141. public static SqlParameter SetValue(this SqlParameter sp, object value)
  1142. {
  1143. sp.Value = value;
  1144. return sp;
  1145. }
  1146. /// <summary>
  1147. /// 为SqlParameter设置SqlDbType. by ngye, on 2013-09-03.
  1148. /// </summary>
  1149. /// <param name="sp"></param>
  1150. /// <returns></returns>
  1151. public static SqlParameter SetSqlDbType(this SqlParameter sp, SqlDbType dbType)
  1152. {
  1153. sp.SqlDbType = dbType;
  1154. return sp;
  1155. }
  1156. /// <summary>
  1157. /// 对可以为空的值作这样的处理,一旦其为空,就设置为DBNull.value.
  1158. /// </summary>
  1159. /// <param name="sp"></param>
  1160. /// <returns></returns>
  1161. public static SqlParameter[] SetDBNull(this SqlParameter[] spArr)
  1162. {
  1163. if (spArr == null || spArr.Length == 0)
  1164. return spArr;
  1165. for (int i = 0; i < spArr.Length; i++)
  1166. {
  1167. SqlParameter sp = spArr[i];
  1168. if (sp.Value == null)
  1169. sp.Value = DBNull.Value;
  1170. }
  1171. return spArr;
  1172. }
  1173. }
  1174. #endregion
  1175. }