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.

1416 lines
50 KiB

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