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

259 lines
9.8 KiB

3 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Data.SqlClient;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace NFine.Data.Extensions
  13. {
  14. public class ERPSqlServerHelper
  15. {
  16. #region [ 连接串相关 ]
  17. /// <summary>
  18. /// 数据中心DB的连接字符串
  19. /// </summary>
  20. public static string ConnectionString = FromMd5( ConfigurationManager.ConnectionStrings["ERPconnstr"].ConnectionString);
  21. /// <summary>
  22. /// 获取同步服务器的连接
  23. /// </summary>
  24. /// <returns></returns>
  25. #region 字符串加解密
  26. /// <summary>
  27. /// MD5加密
  28. /// </summary>
  29. /// <param name="str"></param>
  30. /// <returns></returns>
  31. public static string ToMd5(string str)
  32. {
  33. return Encrypt(str, "&%#@?,:*_");
  34. }
  35. /// <summary>
  36. /// MD5解密
  37. /// </summary>
  38. /// <param name="str"></param>
  39. /// <returns></returns>
  40. public static string FromMd5(string str)
  41. {
  42. //return str;
  43. return Decrypt(str, "&%#@?,:*_");
  44. }
  45. /// <summary>
  46. /// 加密
  47. /// </summary>
  48. /// <param name="strText"></param>
  49. /// <param name="strEncrKey"></param>
  50. /// <returns></returns>
  51. private static String Encrypt(String strText, String strEncrKey)
  52. {
  53. Byte[] byKey = { };
  54. Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  55. try
  56. {
  57. byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
  58. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  59. Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
  60. MemoryStream ms = new MemoryStream();
  61. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV),
  62. CryptoStreamMode.Write);
  63. cs.Write(inputByteArray, 0, inputByteArray.Length);
  64. cs.FlushFinalBlock();
  65. return Convert.ToBase64String(ms.ToArray());
  66. }
  67. catch (Exception ex)
  68. {
  69. return ex.Message;
  70. }
  71. }
  72. /// <summary>
  73. /// 解密
  74. /// </summary>
  75. /// <param name="strText"></param>
  76. /// <param name="sDecrKey"></param>
  77. /// <returns></returns>
  78. private static String Decrypt(String strText, String sDecrKey)
  79. {
  80. Byte[] byKey = { };
  81. Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  82. Byte[] inputByteArray = new byte[strText.Length];
  83. try
  84. {
  85. byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
  86. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  87. inputByteArray = Convert.FromBase64String(strText);
  88. MemoryStream ms = new MemoryStream();
  89. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV),
  90. CryptoStreamMode.Write);
  91. cs.Write(inputByteArray, 0, inputByteArray.Length);
  92. cs.FlushFinalBlock();
  93. System.Text.Encoding encoding = System.Text.Encoding.UTF8;
  94. return encoding.GetString(ms.ToArray());
  95. }
  96. catch (Exception ex)
  97. {
  98. return ex.Message;
  99. }
  100. }
  101. #endregion
  102. private static SqlConnection GetConnectionString()
  103. {
  104. return new SqlConnection(ConnectionString);
  105. }
  106. /// <summary>
  107. /// 根据连接串获取连接
  108. /// </summary>
  109. /// <returns></returns>
  110. private static SqlConnection GetConnByString(string conn)
  111. {
  112. return new SqlConnection(conn);
  113. }
  114. #endregion
  115. #region 数据分页
  116. /// <summary>
  117. /// 摘要:
  118. /// 数据分页
  119. /// 参数:
  120. /// sql:传入要执行sql语句
  121. /// param:参数化
  122. /// orderField:排序字段
  123. /// orderType:排序类型
  124. /// pageIndex:当前页
  125. /// pageSize:页大小
  126. /// count:返回查询条数
  127. /// </summary>
  128. public static DataTable GetPageTable(string sql, DbParameter[] param, string orderField, string orderType, int pageIndex, int pageSize, ref int count)
  129. {
  130. StringBuilder strSql = new StringBuilder();
  131. if (pageIndex == 0)
  132. {
  133. pageIndex = 1;
  134. }
  135. int num = (pageIndex - 1) * pageSize;
  136. int num1 = (pageIndex) * pageSize;
  137. string OrderBy = "";
  138. if (!string.IsNullOrEmpty(orderField))
  139. OrderBy = "Order By " + orderField + " " + orderType + "";
  140. else
  141. OrderBy = "order by (select 0)";
  142. strSql.Append("Select * From (Select ROW_NUMBER() Over (" + OrderBy + ")");
  143. strSql.Append(" As rowNum, * From (" + sql + ") As T ) As N Where rowNum > " + num + " And rowNum <= " + num1 + "");
  144. count = Convert.ToInt32(ExecuteScalar(CommandType.Text, "Select Count(1) From (" + sql + ") As t", param));
  145. IDataReader dr = ExecuteReader(CommandType.Text, strSql.ToString(), param);
  146. return DatabaseReader.ReaderToDataTable(dr);
  147. }
  148. /// <summary>
  149. /// 根据sql语句和参数,返回DataTable
  150. /// </summary>
  151. /// <param name="sql">sql语句</param>
  152. /// <param name="spArr">可变参数</param>
  153. /// <returns>DataTable</returns>
  154. public static DataTable GetDataTableBySql(string sql, params SqlParameter[] spArr)
  155. {
  156. using (SqlConnection conn = GetConnectionString())
  157. {
  158. conn.Open();
  159. SqlCommand cmd = new SqlCommand(sql, conn).AddTimeout();
  160. if (spArr != null && spArr.Length > 0)
  161. cmd.Parameters.AddRange(spArr.SetDBNull());
  162. DataTable dt = cmd.ExecuteDataTable();
  163. return dt;
  164. }
  165. }
  166. /// <summary>
  167. /// 使用提供的参数,执行有结果集返回的数据库操作命令、并返回SqlDataReader对象
  168. /// </summary>
  169. /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
  170. /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>
  171. /// <param name="parameters">执行命令所需的sql语句对应参数</param>
  172. /// <returns>返回SqlDataReader对象</returns>
  173. private static IDataReader ExecuteReader(CommandType cmdType, string cmdText, params DbParameter[] parameters)
  174. {
  175. DbCommand cmd = DbFactory.CreateDbCommand();
  176. DbConnection conn = DbFactory.CreateDbConnection(ConnectionString);
  177. try
  178. {
  179. PrepareCommand(cmd, conn, null, cmdType, cmdText, parameters);
  180. IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  181. cmd.Parameters.Clear();
  182. return rdr;
  183. }
  184. catch (Exception ex)
  185. {
  186. conn.Close();
  187. cmd.Dispose();
  188. //log.Error(ex.Message);
  189. throw;
  190. }
  191. }
  192. /// <summary>
  193. /// 依靠数据库连接字符串connectionString,
  194. /// 使用所提供参数,执行返回首行首列命令
  195. /// </summary>
  196. /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
  197. /// <param name="commandText">存储过程名称或者T-SQL命令行</param>
  198. /// <param name="parameters">执行命令所需的sql语句对应参数</param>
  199. /// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>
  200. private static object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] parameters)
  201. {
  202. try
  203. {
  204. DbCommand cmd = DbFactory.CreateDbCommand();
  205. using (DbConnection connection = DbFactory.CreateDbConnection(ConnectionString))
  206. {
  207. PrepareCommand(cmd, connection, null, cmdType, cmdText, parameters);
  208. object val = cmd.ExecuteScalar();
  209. cmd.Parameters.Clear();
  210. return val;
  211. }
  212. }
  213. catch (Exception ex)
  214. {
  215. //log.Error(ex.Message);
  216. throw;
  217. }
  218. }
  219. /// <summary>
  220. /// 为即将执行准备一个命令
  221. /// </summary>
  222. /// <param name="cmd">SqlCommand对象</param>
  223. /// <param name="conn">SqlConnection对象</param>
  224. /// <param name="isOpenTrans">DbTransaction对象</param>
  225. /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
  226. /// <param name="cmdText">存储过程名称或者T-SQL命令行, e.g. Select * from Products</param>
  227. /// <param name="cmdParms">SqlParameters to use in the command</param>
  228. private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText, DbParameter[] cmdParms)
  229. {
  230. if (conn.State != ConnectionState.Open)
  231. conn.Open();
  232. cmd.Connection = conn;
  233. cmd.CommandText = cmdText;
  234. if (isOpenTrans != null)
  235. cmd.Transaction = isOpenTrans;
  236. cmd.CommandType = cmdType;
  237. if (cmdParms != null)
  238. {
  239. cmd.Parameters.AddRange(cmdParms);
  240. }
  241. }
  242. #endregion
  243. }
  244. }