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

781 lines
28 KiB

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