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

746 lines
26 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
  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. public static int ExecuteNonQuery(string connStr,string sql, params SqlParameter[] spArr)
  164. {
  165. using (SqlConnection conn = new SqlConnection(connStr))
  166. {
  167. conn.Open();
  168. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  169. if (spArr.Length > 0)
  170. cmd.Parameters.AddRange(spArr.SetDBNull());
  171. return cmd.ExecuteNonQuery();
  172. }
  173. }
  174. #endregion
  175. #region [ ExecuteScalar_ForProc ]
  176. /// <summary>
  177. /// 根据存储过程和参数,返回Scalar结果
  178. /// </summary>
  179. /// <param name="proc">存储过程</param>
  180. /// <param name="spArr">可变参数</param>
  181. /// <returns>object</returns>
  182. public static object ExecuteScalar_ForProc(string proc, params SqlParameter[] spArr)
  183. {
  184. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  185. {
  186. conn.Open();
  187. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  188. cmd.CommandType = CommandType.StoredProcedure;
  189. if (spArr.Length > 0)
  190. cmd.Parameters.AddRange(spArr.SetDBNull());
  191. object obj = cmd.ExecuteScalar();
  192. return obj;
  193. }
  194. }
  195. /// <summary>
  196. /// 根据存储过程和参数,返回Scalar结果,但不加上超时设置 ( 避免循环做 AddTimeout )
  197. /// </summary>
  198. /// <param name="proc">存储过程</param>
  199. /// <param name="spArr">可变参数</param>
  200. /// <returns>object</returns>
  201. public static object ExecuteScalar_ForProc_WithoutAddTimeout(string proc, params SqlParameter[] spArr)
  202. {
  203. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  204. {
  205. conn.Open();
  206. SqlCommand cmd = new SqlCommand(proc, conn);
  207. cmd.CommandType = CommandType.StoredProcedure;
  208. if (spArr.Length > 0)
  209. cmd.Parameters.AddRange(spArr.SetDBNull());
  210. object obj = cmd.ExecuteScalar();
  211. return obj;
  212. }
  213. }
  214. #endregion
  215. #region [ ExecuteScalar ]
  216. /// <summary>
  217. /// 根据sql语句和参数,返回Scalar结果
  218. /// </summary>
  219. /// <param name="sql">sql语句</param>
  220. /// <param name="spArr">可变参数</param>
  221. /// <returns>object</returns>
  222. public static object ExecuteScalar(string sql, params SqlParameter[] spArr)
  223. {
  224. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  225. {
  226. conn.Open();
  227. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  228. if (spArr.Length > 0)
  229. cmd.Parameters.AddRange(spArr.SetDBNull());
  230. object obj = cmd.ExecuteScalar();
  231. return obj;
  232. }
  233. }
  234. #endregion
  235. #region [ QueryByProc ]
  236. /// <summary>
  237. /// 根据存储过程及参数,返回DataSet
  238. /// </summary>
  239. /// <returns>DataSet</returns>
  240. public static DataSet GetDataSetByProc(string proc, params SqlParameter[] spArr)
  241. {
  242. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  243. {
  244. conn.Open();
  245. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  246. cmd.CommandType = CommandType.StoredProcedure;
  247. if (spArr.Length > 0)
  248. cmd.Parameters.AddRange(spArr.SetDBNull());
  249. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  250. DataSet ds = new DataSet();
  251. adapter.Fill(ds);
  252. return ds;
  253. }
  254. }
  255. /// <summary>
  256. /// 根据存储过程及参数,返回DataTable
  257. /// </summary>
  258. /// <returns>DataTable</returns>
  259. public static DataTable GetDataTableByProc(string proc, params SqlParameter[] spArr)
  260. {
  261. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  262. {
  263. conn.Open();
  264. SqlCommand cmd = new SqlCommand(proc, conn).AddTimeout();
  265. cmd.CommandType = CommandType.StoredProcedure;
  266. if (spArr.Length > 0)
  267. cmd.Parameters.AddRange(spArr.SetDBNull());
  268. DataTable dt = cmd.ExecuteDataTable();
  269. return dt;
  270. }
  271. }
  272. /// <summary>
  273. /// 根据sql语句和参数,返回DataRow
  274. /// </summary>
  275. /// <param name="sql">sql语句</param>
  276. /// <param name="spArr">可变参数</param>
  277. /// <returns>DataRow</returns>
  278. public static DataRow GetDataRowByProc(string proc, params SqlParameter[] spArr)
  279. {
  280. DataTable dt = GetDataTableByProc(proc, spArr);
  281. if (dt == null || dt.Rows.Count == 0)
  282. return null;
  283. return dt.Rows[0];
  284. }
  285. #endregion
  286. #region [ Query ]
  287. /// <summary>
  288. /// 根据sql语句和参数,返回DataSet
  289. /// </summary>
  290. /// <param name="sql">sql语句</param>
  291. /// <param name="spArr">可变参数</param>
  292. /// <returns>DataSet</returns>
  293. public static DataSet GetDataSetBySql(string sql, params SqlParameter[] spArr)
  294. {
  295. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  296. {
  297. conn.Open();
  298. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  299. if (spArr.Length > 0)
  300. cmd.Parameters.AddRange(spArr.SetDBNull());
  301. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  302. DataSet ds = new DataSet();
  303. adapter.Fill(ds);
  304. return ds;
  305. }
  306. }
  307. /// <summary>
  308. /// 根据sql语句和参数,返回DataTable
  309. /// </summary>
  310. /// <param name="sql">sql语句</param>
  311. /// <param name="spArr">可变参数</param>
  312. /// <returns>DataTable</returns>
  313. public static DataTable GetDataTableBySql(string sql, params SqlParameter[] spArr)
  314. {
  315. using (SqlConnection conn = SqlHelper.GetDataCenterConn())
  316. {
  317. conn.Open();
  318. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  319. if (spArr.Length > 0)
  320. cmd.Parameters.AddRange(spArr.SetDBNull());
  321. DataTable dt = cmd.ExecuteDataTable();
  322. return dt;
  323. }
  324. }
  325. /// <summary>
  326. /// 根据sql语句和参数,返回DataRow
  327. /// </summary>
  328. /// <param name="sql">sql语句</param>
  329. /// <param name="spArr">可变参数</param>
  330. /// <returns>DataRow</returns>
  331. public static DataRow GetDataRowBySql(string sql, params SqlParameter[] spArr)
  332. {
  333. DataTable dt = GetDataTableBySql(sql, spArr);
  334. if (dt == null || dt.Rows.Count == 0)
  335. return null;
  336. return dt.Rows[0];
  337. }
  338. #endregion
  339. #region [ GetValue ]
  340. public static object GetValue(DataRow dr, string fieldName, object replaceValue)
  341. {
  342. if (dr.IsNull(fieldName))
  343. return replaceValue;
  344. return dr[fieldName];
  345. }
  346. public static object GetValue(DataRow dr, int idx, object replaceValue)
  347. {
  348. if (dr.IsNull(idx))
  349. return replaceValue;
  350. return dr[idx];
  351. }
  352. #endregion
  353. #region [ GetString ]
  354. public static string GetString(DataRow dr, string fieldName, string replaceValue)
  355. {
  356. if (dr.IsNull(fieldName))
  357. return replaceValue;
  358. return Convert.ToString(dr[fieldName]);
  359. }
  360. public static string GetString(DataRow dr, int idx, string replaceValue)
  361. {
  362. if (dr.IsNull(idx))
  363. return replaceValue;
  364. return Convert.ToString(dr[idx]);
  365. }
  366. #endregion
  367. #region [ GetDateTime ]
  368. public static DateTime GetDateTime(DataRow dr, string fieldName, DateTime replaceValue)
  369. {
  370. if (dr.IsNull(fieldName))
  371. return replaceValue;
  372. return Convert.ToDateTime(dr[fieldName]);
  373. }
  374. public static DateTime GetDateTime(DataRow dr, int idx, DateTime replaceValue)
  375. {
  376. if (dr.IsNull(idx))
  377. return replaceValue;
  378. return Convert.ToDateTime(dr[idx]);
  379. }
  380. #endregion
  381. #region [ 非数据中心库操作 ]
  382. #region [ ExecuteScalar ]
  383. /// <summary>
  384. /// 根据sql语句和参数,返回Scalar结果
  385. /// </summary>
  386. /// <param name="connString">连接串</param>
  387. /// <param name="sql">sql语句</param>
  388. /// <param name="spArr">可变参数</param>
  389. /// <returns>object</returns>
  390. public static object ExecuteScalarWithConn(string connString, string sql, params SqlParameter[] spArr)
  391. {
  392. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  393. {
  394. conn.Open();
  395. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  396. if (spArr.Length > 0)
  397. cmd.Parameters.AddRange(spArr.SetDBNull());
  398. object obj = cmd.ExecuteScalar();
  399. return obj;
  400. }
  401. }
  402. #endregion
  403. #region [ ExecuteNonQuery ]
  404. /// <summary>
  405. /// 根据sql语句和参数,返回受影响行数
  406. /// </summary>
  407. /// <param name="connString">连接串</param>
  408. /// <param name="sql">sql语句</param>
  409. /// <param name="spArr">可变参数</param>
  410. /// <returns>受影响行数</returns>
  411. public static int ExecuteNonQueryWithConn(string connString, string sql, params SqlParameter[] spArr)
  412. {
  413. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  414. {
  415. conn.Open();
  416. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  417. if (spArr.Length > 0)
  418. cmd.Parameters.AddRange(spArr.SetDBNull());
  419. return cmd.ExecuteNonQuery();
  420. }
  421. }
  422. #endregion
  423. #region [ Query ]
  424. /// <summary>
  425. /// 根据sql语句和参数,返回DataTable
  426. /// </summary>
  427. /// <param name="connString">连接串</param>
  428. /// <param name="sql">sql语句</param>
  429. /// <param name="spArr">可变参数</param>
  430. /// <returns>DataTable</returns>
  431. public static DataTable GetDataTableBySqlWithConn(string connString, string sql, params SqlParameter[] spArr)
  432. {
  433. using (SqlConnection conn = SqlHelper.GetConnByString(connString))
  434. {
  435. conn.Open();
  436. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  437. if (spArr.Length > 0)
  438. cmd.Parameters.AddRange(spArr.SetDBNull());
  439. DataTable dt = cmd.ExecuteDataTable();
  440. return dt;
  441. }
  442. }
  443. /// <summary>
  444. /// 根据sql语句和参数,返回DataRow
  445. /// </summary>
  446. /// <param name="connString">连接串</param>
  447. /// <param name="sql">sql语句</param>
  448. /// <param name="spArr">可变参数</param>
  449. /// <returns>DataRow</returns>
  450. public static DataRow GetDataRowBySqlWithConn(string connString, string sql, params SqlParameter[] spArr)
  451. {
  452. DataTable dt = GetDataTableBySqlWithConn(connString, sql, spArr);
  453. if (dt == null || dt.Rows.Count == 0)
  454. return null;
  455. return dt.Rows[0];
  456. }
  457. #endregion
  458. #endregion
  459. #region [ 根据SQL文件路径执行 ]
  460. /// <summary>
  461. /// 执行SQL文件
  462. /// </summary>
  463. /// <param name="connString"></param>
  464. /// <param name="filePath"></param>
  465. /// <returns></returns>
  466. public static bool ExecuteNonQueryWithConnAndSqlFilePath(string connString, string filePath)
  467. {
  468. string sql = System.IO.File.ReadAllText(filePath);
  469. return ExecuteNonQueryWithConnAndGO(connString, sql);
  470. }
  471. #endregion
  472. #region [ 执行带Go语句 ]
  473. /// <summary>
  474. /// 执行带"GO"的SQL,返回最后一条SQL的受影响行数
  475. /// </summary>
  476. /// <param name="connString">连接串</param>
  477. /// <param name="sql">sql语句</param>
  478. /// <returns>返回最后一条SQL的受影响行数</returns>
  479. public static bool ExecuteNonQueryWithConnAndGO(string connString, string sql)
  480. {
  481. bool result = true;
  482. string[] arr = System.Text.RegularExpressions.Regex.Split(sql, @"\bGO\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  483. using (SqlConnection conn = GetConnByString(connString))
  484. {
  485. conn.Open();
  486. SqlCommand cmd = new SqlCommand().AddTimeout();
  487. cmd.Connection = conn;
  488. SqlTransaction tx = conn.BeginTransaction();
  489. cmd.Transaction = tx;
  490. try
  491. {
  492. for (int n = 0; n < arr.Length; n++)
  493. {
  494. string strsql = arr[n];
  495. if (strsql.Trim().Length > 1 && strsql.Trim().Replace(";", "") != "")
  496. {
  497. cmd.CommandText = strsql;
  498. cmd.ExecuteNonQuery();
  499. }
  500. }
  501. tx.Commit();
  502. }
  503. catch (System.Data.SqlClient.SqlException E)
  504. {
  505. tx.Rollback();
  506. result = false;
  507. //return -1;
  508. throw new Exception(E.Message);
  509. }
  510. finally
  511. {
  512. if (conn.State != ConnectionState.Closed)
  513. {
  514. conn.Close();
  515. conn.Dispose();
  516. }
  517. }
  518. }
  519. return result;
  520. }
  521. #endregion
  522. /// <summary>
  523. /// 设置Sql参数
  524. /// </summary>
  525. /// <param name="parameterName"></param>
  526. /// <param name="value"></param>
  527. /// <param name="dbType"></param>
  528. /// <returns></returns>
  529. public static SqlParameter SetSqlParameter(string parameterName, object value, SqlDbType dbType)
  530. {
  531. if (value == null || string.IsNullOrEmpty(value.ToString()))
  532. {
  533. return new SqlParameter(parameterName, DBNull.Value);
  534. }
  535. SqlParameter sp = new SqlParameter(parameterName, value);
  536. sp.SqlDbType = dbType;
  537. return sp;
  538. }
  539. /// <summary>
  540. /// 根据sql及带 in 的id参数列表, 得到DataTable
  541. /// </summary>
  542. /// <param name="sql">带in ( {0} )的sql</param>
  543. /// <param name="ids">以逗号分隔的id字符串</param>
  544. /// <param name="idDbType">id的Sql数据类型</param>
  545. /// <returns>DataTable</returns>
  546. public static DataTable GetDataTableWithIn(string sql, string ids, SqlDbType idDbType)
  547. {
  548. SqlParameter[] spArr = GetWithInSqlParameters(ref sql, ids, idDbType);
  549. return GetDataTableBySql(sql, spArr);
  550. }
  551. /// <summary>
  552. /// 根据sql及带 in 的id参数列表, 得到受影响行数
  553. /// </summary>
  554. /// <param name="sql">带in ( {0} )的sql</param>
  555. /// <param name="ids">以逗号分隔的id字符串</param>
  556. /// <param name="idDbType">id的Sql数据类型</param>
  557. /// <returns>DataTable</returns>
  558. public static int ExecuteNonQueryWithIn(string sql, string ids, SqlDbType idDbType)
  559. {
  560. SqlParameter[] spArr = GetWithInSqlParameters(ref sql, ids, idDbType);
  561. return ExecuteNonQuery(sql, spArr);
  562. }
  563. #region [ 带 in 不确定参数的执行方法 ]
  564. /// <summary>
  565. /// 获取带 in 的sql参数列表
  566. /// </summary>
  567. /// <param name="sql">带in ( {0} )的sql</param>
  568. /// <param name="ids">以逗号分隔的id字符串</param>
  569. /// <param name="idDbType">id的Sql数据类型</param>
  570. /// <returns>sql参数列表</returns>
  571. public static SqlParameter[] GetWithInSqlParameters(ref string sql, string ids, SqlDbType idDbType)
  572. {
  573. if (string.IsNullOrEmpty(ids))
  574. {
  575. return null;
  576. }
  577. string[] idArr = ids.Split(',');
  578. //组建sql在in中的字符串
  579. StringBuilder sbCondition = new StringBuilder();
  580. List<SqlParameter> spList = new List<SqlParameter>();
  581. for (int i = 0; i < idArr.Length; i++)
  582. {
  583. string id = idArr[i];
  584. string spName = string.Format("@id{0}", i);
  585. sbCondition.AppendFormat("{0},", spName);
  586. spList.Add(SetSqlParameter(spName, id, idDbType));
  587. }
  588. //重新构建sql
  589. sql = string.Format(sql, sbCondition.ToString().TrimEnd(','));
  590. return spList.ToArray();
  591. }
  592. #endregion
  593. }//end of class
  594. #region [ SqlHelper 的扩展方法类 ]
  595. /// <summary>
  596. /// 扩展方法类
  597. /// </summary>
  598. public static class SqlHelperExtensionMethods
  599. {
  600. /// <summary>
  601. /// 新建SqlCommand对象时, 自动加上指定的 CommandTimeout. by ngye, on 2013-07-11.
  602. /// </summary>
  603. /// <param name="cmd">SqlCommand对象</param>
  604. /// <returns>SqlCommand对象</returns>
  605. public static SqlCommand AddTimeout(this SqlCommand cmd)
  606. {
  607. cmd.CommandTimeout = SqlHelper.CommandTimeout;
  608. return cmd;
  609. }
  610. /// <summary>
  611. /// 新建SqlBulkCopy对象时, 自动加上指定的 BulkCopyTimeout. by ngye, on 2013-08-30.
  612. /// </summary>
  613. /// <param name="cmd">SqlBulkCopy对象</param>
  614. /// <returns>SqlBulkCopy对象</returns>
  615. public static SqlBulkCopy AddTimeout(this SqlBulkCopy bulkCopy)
  616. {
  617. bulkCopy.BulkCopyTimeout = SqlHelper.CommandTimeout;
  618. return bulkCopy;
  619. }
  620. /// <summary>
  621. /// 执行cmd得到 DataTable. by ngye, on 2013-08-01
  622. /// </summary>
  623. /// <param name="cmd"></param>
  624. /// <returns></returns>
  625. public static DataTable ExecuteDataTable(this SqlCommand cmd)
  626. {
  627. DataTable dt = new DataTable();
  628. using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
  629. {
  630. adapter.Fill(dt);
  631. }
  632. return dt;
  633. }
  634. /// <summary>
  635. /// 为SqlParameter设置参数. by ngye, on 2013-08-15.
  636. /// </summary>
  637. /// <param name="sp"></param>
  638. /// <returns></returns>
  639. public static SqlParameter SetValue(this SqlParameter sp, object value)
  640. {
  641. sp.Value = value;
  642. return sp;
  643. }
  644. /// <summary>
  645. /// 为SqlParameter设置SqlDbType. by ngye, on 2013-09-03.
  646. /// </summary>
  647. /// <param name="sp"></param>
  648. /// <returns></returns>
  649. public static SqlParameter SetSqlDbType(this SqlParameter sp, SqlDbType dbType)
  650. {
  651. sp.SqlDbType = dbType;
  652. return sp;
  653. }
  654. /// <summary>
  655. /// 对可以为空的值作这样的处理,一旦其为空,就设置为DBNull.value.
  656. /// </summary>
  657. /// <param name="sp"></param>
  658. /// <returns></returns>
  659. public static SqlParameter[] SetDBNull(this SqlParameter[] spArr)
  660. {
  661. if (spArr == null || spArr.Length == 0)
  662. return spArr;
  663. for (int i = 0; i < spArr.Length; i++)
  664. {
  665. SqlParameter sp = spArr[i];
  666. if (sp.Value == null)
  667. sp.Value = DBNull.Value;
  668. }
  669. return spArr;
  670. }
  671. public static string HttpPost(string url, string body)
  672. {
  673. try
  674. {
  675. Encoding encoding = Encoding.UTF8;
  676. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  677. request.Method = "POST";
  678. request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
  679. request.ContentType = "application/json; charset=utf-8";
  680. byte[] buffer = encoding.GetBytes(body);
  681. request.ContentLength = buffer.Length;
  682. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  683. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  684. using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
  685. {
  686. return reader.ReadToEnd();
  687. }
  688. }
  689. catch (WebException ex)
  690. {
  691. throw new Exception(ex.Message);
  692. }
  693. }
  694. }
  695. #endregion
  696. }