1 using System; 2 using System.Collections.Specialized; 3 using System.IO; 4 using System.Net; 5 using System.Text; 6 using System.Text.RegularExpressions; 7 using System.Collections.Generic; 8 using System.Configuration; 9 using System.Data; 10 using System.Data.SqlClient; 11 using System.Security.Cryptography.X509Certificates; 12 using System.Net.Security; 13 using System.Reflection; 14 using System.ComponentModel; 15 16 namespace DBUtility 17 { 18 public class DButility 19 { 20 private static Random ran = new Random(); 21 private static readonly int TIMEOUT = 5000; 22 #region DBNull类型转换 23 public static long ToInt64(object value) 24 { 25 return (Convert.IsDBNull(value)) ? 0 : Convert.ToInt64(value); 26 } 27 28 public static int ToInt32(object value) 29 { 30 return (Convert.IsDBNull(value)) ? 0 : Convert.ToInt32(value); 31 } 32 33 public static short ToInt16(object value) 34 { 35 return (Convert.IsDBNull(value)) ? (short)0 : Convert.ToInt16(value); 36 } 37 38 public static string ToString(object value) 39 { 40 return value.ToString(); 41 } 42 43 public static decimal ToDecimal(object value) 44 { 45 return (Convert.IsDBNull(value)) ? 0 : Convert.ToDecimal(value); 46 } 47 48 public static DateTime ToDateTime(object value) 49 { 50 return (Convert.IsDBNull(value)) ? DateTime.MinValue : Convert.ToDateTime(value); 51 } 52 #endregion 53 54 #region AES 加密/解密 55 /// <summary> 56 /// AES 加密 57 /// </summary> 58 /// <param name="str">明文(待加密)</param> 59 /// <param name="key">密文</param> 60 /// <returns></returns> 61 public static string AesEncryptToHex(string str, string key) 62 { 63 if (string.IsNullOrEmpty(str)) return null; 64 Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); //命名空间: using System.Text; 65 66 System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged 67 { 68 Key = Encoding.UTF8.GetBytes(key), 69 Mode = System.Security.Cryptography.CipherMode.ECB, 70 Padding = System.Security.Cryptography.PaddingMode.PKCS7 71 }; 72 73 System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); 74 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 75 76 var hex = BitConverter.ToString(resultArray, 0).Replace("-", string.Empty).ToLower(); 77 return hex; 78 } 79 80 /// <summary> 81 /// AES 解密 82 /// </summary> 83 /// <param name="str">明文(待解密)</param> 84 /// <param name="key">密文</param> 85 /// <returns></returns> 86 public static string AesDecryptFromHex(string str, string key) 87 { 88 if (string.IsNullOrEmpty(str)) return null; 89 var toEncryptArray = new byte[str.Length / 2]; 90 for (var x = 0; x < toEncryptArray.Length; x++) 91 { 92 var i = Convert.ToInt32(str.Substring(x * 2, 2), 16); 93 toEncryptArray[x] = (byte)i; 94 } 95 96 //Byte[] toEncryptArray = Convert.FromBase64String(str); 97 98 System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged 99 { 100 Key = Encoding.UTF8.GetBytes(key), 101 Mode = System.Security.Cryptography.CipherMode.ECB, 102 Padding = System.Security.Cryptography.PaddingMode.PKCS7 103 }; 104 105 System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); 106 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 107 108 return Encoding.UTF8.GetString(resultArray); 109 } 110 #endregion 111 112 #region 获取时间戳,取随机数 113 /// <summary> 114 /// 获取时间戳 115 /// </summary> 116 /// <returns></returns> 117 public static long GetTimeStamp() 118 { 119 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); 120 return Convert.ToInt64(ts.TotalSeconds); 121 } 122 123 /// <summary> 124 /// 取随机数 125 /// </summary> 126 /// <param name="min"></param> 127 /// <param name="max"></param> 128 /// <returns></returns> 129 public static int GetRandom(int min, int max) 130 { 131 return ran.Next(min, max); 132 } 133 134 /// <summary> 135 /// 获取当前本地时间戳 136 /// </summary> 137 /// <returns></returns> 138 public static long GetCurrentTimeUnix() 139 { 140 TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1))); 141 long t = (long)cha.TotalSeconds; 142 return t; 143 } 144 145 /// <summary> 146 /// 时间戳转换为本地时间对象 147 /// </summary> 148 /// <returns></returns> 149 public static DateTime GetUnixDateTime(long unix) 150 { 151 //long unix = 1500863191; 152 DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 153 DateTime newTime = dtStart.AddSeconds(unix); 154 return newTime; 155 } 156 157 /// <summary> 158 /// Unicode转字符串 159 /// </summary> 160 /// <param name="source">经过Unicode编码的字符串</param> 161 /// <returns>正常字符串</returns> 162 public static string UnicodeToString(string source) 163 { 164 return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace( 165 source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16))); 166 } 167 168 /// <summary> 169 /// Stream流转化为字符串 170 /// </summary> 171 /// <returns></returns> 172 public static string StreamToString(Stream stream) 173 { 174 if (stream == null || stream.Length == 0) 175 { 176 return string.Empty; 177 } 178 StreamReader sr = new StreamReader(stream); 179 return sr.ReadToEnd(); 180 } 181 182 /// <summary> 183 /// RequestForm转换成String, key=value格式 184 /// </summary> 185 /// <returns></returns> 186 public static string RequestFormToString(NameValueCollection form) 187 { 188 if (form == null) 189 { 190 return null; 191 } 192 193 string strTemp = string.Empty; 194 195 String[] requestItem = form.AllKeys; 196 for (int i = 0; i < requestItem.Length; i++) 197 { 198 strTemp += requestItem[i] + "=" + form[requestItem[i]] + "&"; 199 } 200 201 strTemp = strTemp.TrimEnd('&'); 202 return strTemp; 203 } 204 #endregion 205 206 #region HttpUtils 207 208 public static string HttpPost(string Url, string mobiles, string content) 209 { 210 string postData = string.Format("mobiles={0}&content={1}", mobiles, content); 211 212 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 213 System.Net.ServicePointManager.DefaultConnectionLimit = 200; 214 request.Method = "POST"; 215 request.KeepAlive = false; 216 request.ContentType = "application/x-www-form-urlencoded"; 217 request.ContentLength = Encoding.UTF8.GetByteCount(postData); 218 Stream myRequestStream = request.GetRequestStream(); 219 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); 220 myStreamWriter.Write(postData, 0, postData.Length); 221 myStreamWriter.Close(); 222 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 223 224 Stream myResponseStream = response.GetResponseStream(); 225 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 226 string retString = myStreamReader.ReadToEnd(); 227 myStreamReader.Close(); 228 229 myResponseStream.Close(); 230 231 response = null; 232 request = null; 233 return retString; 234 } 235 236 237 238 /// <summary> 239 /// 指定Post地址使用Get 方式获取全部字符串 240 /// </summary> 241 /// <param name="url">请求后台地址</param> 242 /// <returns></returns> 243 public static string Post(string url, Dictionary<string, string> dic) 244 { 245 string result = ""; 246 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 247 string mobiles = dic["mobiles"]; 248 string content = dic["content"]; 249 req.Method = "POST"; 250 req.ContentType = "application/x-www-form-urlencoded"; 251 #region 添加Post 参数 252 StringBuilder builder = new StringBuilder(); 253 int i = 0; 254 foreach (var item in dic) 255 { 256 if (i > 0) 257 builder.Append("&"); 258 builder.AppendFormat("{0}={1}", item.Key, item.Value); 259 i++; 260 } 261 byte[] data = Encoding.UTF8.GetBytes(builder.ToString()); 262 req.ContentLength = data.Length; 263 using (Stream reqStream = req.GetRequestStream()) 264 { 265 reqStream.Write(data, 0, data.Length); 266 reqStream.Close(); 267 } 268 #endregion 269 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 270 Stream stream = resp.GetResponseStream(); 271 //获取响应内容 272 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 273 { 274 result = reader.ReadToEnd(); 275 } 276 return result; 277 } 278 279 /// <summary> 280 /// 指定地址使用Get 方式获取全部字符串 281 /// </summary> 282 /// <param name="url">请求后台地址</param> 283 /// <returns></returns> 284 public static string Get(string url, Dictionary<string, string> dic) 285 { 286 string result = ""; 287 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 288 string uname = dic["username"]; 289 string pwd = dic["password"]; 290 req.Method = "GET"; 291 req.ContentType = "application/x-www-form-urlencoded"; 292 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 293 Stream stream = resp.GetResponseStream(); 294 //获取响应内容 295 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 296 { 297 result = reader.ReadToEnd(); 298 } 299 return result; 300 } 301 302 public static string PostSend(string url, string param) 303 { 304 return PostSend(url, "UTF-8", param); 305 } 306 307 public static string PostSend(string url, string encoding, string param, string contentType = "application/x-www-form-urlencoded") 308 { 309 try 310 { 311 byte[] postData = Encoding.UTF8.GetBytes(param); 312 313 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 314 Encoding myEncoding = Encoding.UTF8; 315 request.Method = "POST"; 316 request.KeepAlive = false; 317 request.AllowAutoRedirect = true; 318 request.ContentType = contentType; 319 request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; 320 request.ContentLength = postData.Length; 321 request.Timeout = TIMEOUT; 322 323 System.IO.Stream outputStream = request.GetRequestStream(); 324 outputStream.Write(postData, 0, postData.Length); 325 outputStream.Close(); 326 327 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 328 329 Stream responseStream = response.GetResponseStream(); 330 331 StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); 332 333 string retVal = reader.ReadToEnd(); 334 335 reader.Close(); 336 337 return retVal; 338 } 339 catch (Exception ex) 340 { 341 LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message); 342 return ex.Message; 343 } 344 } 345 346 public static string PostSendWithCert(string url, string param) 347 { 348 return PostSendWithCert(url, "UTF-8", param); 349 } 350 351 public static string PostSendWithCert(string url, string encoding, string param, string contentType = "application/x-www-form-urlencoded") 352 { 353 try 354 { 355 string cert = System.Configuration.ConfigurationManager.AppSettings["CertPath"]; 356 string password = System.Configuration.ConfigurationManager.AppSettings["xcxMchId"]; 357 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 358 X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); 359 360 byte[] postData = Encoding.UTF8.GetBytes(param); 361 362 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 363 Encoding myEncoding = Encoding.UTF8; 364 request.ClientCertificates.Add(cer); 365 request.Method = "POST"; 366 request.KeepAlive = false; 367 request.AllowAutoRedirect = true; 368 request.ContentType = contentType; 369 request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; 370 request.ContentLength = postData.Length; 371 request.Timeout = TIMEOUT; 372 373 System.IO.Stream outputStream = request.GetRequestStream(); 374 outputStream.Write(postData, 0, postData.Length); 375 outputStream.Close(); 376 377 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 378 379 Stream responseStream = response.GetResponseStream(); 380 381 StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); 382 383 string retVal = reader.ReadToEnd(); 384 385 reader.Close(); 386 387 return retVal; 388 } 389 catch (Exception ex) 390 { 391 LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message); 392 return ex.Message; 393 } 394 } 395 396 /// <summary> 397 /// 发请求获取图片到本地路径 398 /// </summary> 399 /// <param name="url"></param> 400 /// <param name="param"></param> 401 /// <param name="pathName"></param> 402 /// <param name="contentType"></param> 403 public static void PostSaveToFile(string url, string param, string pathName, string contentType = "application/x-www-form-urlencoded") 404 { 405 try 406 { 407 byte[] postData = Encoding.UTF8.GetBytes(param); 408 409 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 410 Encoding myEncoding = Encoding.UTF8; 411 request.Method = "POST"; 412 request.KeepAlive = false; 413 request.AllowAutoRedirect = true; 414 request.ContentType = contentType; 415 request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; 416 request.ContentLength = postData.Length; 417 request.Timeout = TIMEOUT; 418 419 System.IO.Stream outputStream = request.GetRequestStream(); 420 outputStream.Write(postData, 0, postData.Length); 421 outputStream.Close(); 422 423 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 424 425 Stream responseStream = response.GetResponseStream(); 426 427 System.Drawing.Image.FromStream(responseStream).Save(pathName); 428 } 429 catch (Exception ex) 430 { 431 LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message); 432 } 433 } 434 435 public static string HttpGet(string Url, string postDataStr = "") 436 { 437 try 438 { 439 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); 440 // https 441 if (Url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 442 { 443 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 444 request.ProtocolVersion = HttpVersion.Version10; 445 } 446 447 request.Method = "GET"; 448 request.ContentType = "text/html;charset=UTF-8"; 449 request.Timeout = 3000; 450 451 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 452 Stream myResponseStream = response.GetResponseStream(); 453 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 454 string retString = myStreamReader.ReadToEnd(); 455 myStreamReader.Close(); 456 myResponseStream.Close(); 457 458 return retString; 459 } 460 catch (Exception e) 461 { 462 Console.WriteLine(e.Message); 463 return null; 464 } 465 } 466 467 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 468 { 469 return true; //总是接受 470 } 471 #endregion 472 473 #region MD5加密 474 475 /// <summary> 476 /// 477 /// </summary> 478 /// <param name="sDataIn"></param> 479 /// <param name="move">给空即可</param> 480 /// <returns></returns> 481 public static string GetMD532(string sDataIn, string move) 482 { 483 System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); 484 byte[] bytValue, bytHash; 485 bytValue = System.Text.Encoding.UTF8.GetBytes(move + sDataIn); 486 bytHash = md5.ComputeHash(bytValue); 487 md5.Clear(); 488 string sTemp = ""; 489 for (int i = 0; i < bytHash.Length; i++) 490 { 491 sTemp += bytHash[i].ToString("x").PadLeft(2, '0'); 492 } 493 return sTemp; 494 } 495 496 public static string GetMD516(string ConvertString) 497 { 498 System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); 499 string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); 500 t2 = t2.Replace("-", ""); 501 502 t2 = t2.ToLower(); 503 504 return t2; 505 } 506 #endregion 507 } 508 #region log4net 日志类 509 public class LogHelper 510 { 511 //在 <configuration></configuration>里面添加下面配置 512 513 // <configSections> 514 // <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> 515 //</configSections> 516 517 // <log4net> 518 // <logger name="logerror"> 519 // <level value="ERROR"/> 520 // <appender-ref ref="ErrorAppender"/> 521 // </logger> 522 // <logger name="loginfo"> 523 // <level value="INFO"/> 524 // <appender-ref ref="InfoAppender"/> 525 // </logger> 526 // <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> 527 // <param name="File" value="Log\Error\"/> 528 // <param name="AppendToFile" value="true"/> 529 // <param name="CountDirection" value="-1"/> 530 // <param name="MaxSizeRollBackups" value="15"/> 531 // <param name="MaximumFileSize" value="5MB"/> 532 // <param name="lockingModel" type="log4net.Appender.FileAppender+MinimalLock"/> 533 // <rollingStyle value="Date"/> 534 // <datePattern value="yyyyMMdd'.txt'"/> 535 // <staticLogFileName value="false"/> 536 // <layout type="log4net.Layout.PatternLayout"> 537 // <conversionPattern value="%d [%t]%c %m%n"/> 538 // </layout> 539 // </appender> 540 // <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> 541 // <param name="File" value="Log\Info\"/> 542 // <param name="AppendToFile" value="true"/> 543 // <param name="CountDirection" value="-1"/> 544 // <param name="MaxSizeRollBackups" value="15"/> 545 // <param name="MaximumFileSize" value="5MB"/> 546 // <param name="lockingModel" type="log4net.Appender.FileAppender+MinimalLock"/> 547 // <rollingStyle value="Date"/> 548 // <datePattern value="yyyyMMdd'.txt'"/> 549 // <staticLogFileName value="false"/> 550 // <layout type="log4net.Layout.PatternLayout"> 551 // <conversionPattern value="%d [%t]%c %m%n"/> 552 // </layout> 553 // </appender> 554 //</log4net> 555 556 557 private static readonly log4net.ILog ILogInfo = log4net.LogManager.GetLogger("loginfo"); //添加log4net 引用 558 559 public static readonly log4net.ILog ILogError = log4net.LogManager.GetLogger("logerror"); 560 561 public static void Info(string msg) 562 { 563 ILogInfo.Info(msg); 564 } 565 566 public static void Error(string msg) 567 { 568 ILogError.Error(msg); 569 } 570 571 /// <summary> 572 /// 废弃 改用FileNameError 573 /// </summary> 574 /// <param name="type"></param> 575 /// <param name="msg"></param> 576 public static void TypeError(string type, string msg) 577 { 578 // eg: type=Order, msg=数据库更新失败, OrderId:111222333 579 // msg:[Order] 数据库更新失败, OrderId:111222333 580 ILogError.Error("[" + type + "] " + msg); 581 } 582 583 public static void FileNameInfo(string fileName, string msg) 584 { 585 ILogInfo.Info(fileName + " " + msg); 586 } 587 588 public static void FileNameError(string fileName, string msg) 589 { 590 ILogError.Error(fileName + " " + msg); 591 } 592 } 593 #endregion 594 595 #region DataTable,DataSet,list集合 互转 596 public class ModelHandler<T> where T : new() 597 { 598 #region DataSet=>List 599 /// <summary> 600 /// 填充对象列表:用DataSet的第一个表填充实体类 601 /// </summary> 602 /// <param name="ds">DataSet</param> 603 /// <returns></returns> 604 public List<T> FillModelByDataSet(DataSet ds) 605 { 606 if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0) 607 { 608 return null; 609 } 610 else 611 { 612 return FillModelByDataTable(ds.Tables[0]); 613 } 614 } 615 #endregion 616 617 #region DataTable=>List 618 619 620 #region 621 622 /// <summary> 623 /// 类型枚举 624 /// </summary> 625 private enum ModelType 626 { 627 //值类型 628 Struct, 629 630 Enum, 631 632 //引用类型 633 String, 634 635 Object, 636 Else 637 } 638 639 private static ModelType GetModelType(Type modelType) 640 { 641 //值类型 642 if (modelType.IsEnum) 643 { 644 return ModelType.Enum; 645 } 646 //值类型 647 if (modelType.IsValueType) 648 { 649 return ModelType.Struct; 650 } 651 //引用类型 特殊类型处理 652 if (modelType == typeof(string)) 653 { 654 return ModelType.String; 655 } 656 //引用类型 特殊类型处理 657 return modelType == typeof(object) ? ModelType.Object : ModelType.Else; 658 } 659 660 #endregion 661 662 /// <summary> 663 /// 填充对象列表:用DataTable填充实体类 664 /// </summary> 665 public List<T> FillModelByDataTable(DataTable dt) 666 { 667 if (dt == null || dt.Rows.Count == 0) 668 { 669 return null; 670 } 671 List<T> modelList = new List<T>(); 672 foreach (DataRow dr in dt.Rows) 673 { 674 //T model = (T)Activator.CreateInstance(typeof(T)); 675 T model = new T(); 676 for (int i = 0; i < dr.Table.Columns.Count; i++) 677 { 678 PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName); 679 if (propertyInfo != null && dr[i] != DBNull.Value) 680 propertyInfo.SetValue(model, dr[i], null); 681 } 682 683 modelList.Add(model); 684 } 685 return modelList; 686 } 687 688 689 690 /// <summary> 691 /// datatable转换为List<T>集合 692 /// </summary> 693 /// <typeparam name="T"></typeparam> 694 /// <param name="table"></param> 695 /// <returns></returns> 696 public static List<T> DataTableToList<T>(DataTable table) 697 { 698 var list = new List<T>(); 699 foreach (DataRow item in table.Rows) 700 { 701 list.Add(DataRowToModel<T>(item)); 702 } 703 return list; 704 } 705 #endregion 706 707 708 709 710 #region DataRow=>Model 711 /// <summary> 712 /// 填充对象:用DataRow填充实体类 713 /// </summary> 714 public T FillModelByDataRow(DataRow dr) 715 { 716 if (dr == null) 717 { 718 return default(T); 719 } 720 721 //T model = (T)Activator.CreateInstance(typeof(T)); 722 T model = new T(); 723 724 for (int i = 0; i < dr.Table.Columns.Count; i++) 725 { 726 PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName); 727 if (propertyInfo != null && dr[i] != DBNull.Value) 728 propertyInfo.SetValue(model, dr[i], null); 729 } 730 return model; 731 } 732 733 734 public static T DataRowToModel<T>(DataRow row) 735 { 736 T model; 737 var type = typeof(T); 738 var modelType = GetModelType(type); 739 switch (modelType) 740 { 741 //值类型 742 case ModelType.Struct: 743 { 744 model = default(T); 745 if (row[0] != null) 746 model = (T)row[0]; 747 } 748 break; 749 //值类型 750 case ModelType.Enum: 751 { 752 model = default(T); 753 if (row[0] != null) 754 { 755 var fiType = row[0].GetType(); 756 if (fiType == typeof(int)) 757 { 758 model = (T)row[0]; 759 } 760 else if (fiType == typeof(string)) 761 { 762 model = (T)Enum.Parse(typeof(T), row[0].ToString()); 763 } 764 } 765 } 766 break; 767 //引用类型 c#对string也当做值类型处理 768 case ModelType.String: 769 { 770 model = default(T); 771 if (row[0] != null) 772 model = (T)row[0]; 773 } 774 break; 775 //引用类型 直接返回第一行第一列的值 776 case ModelType.Object: 777 { 778 model = default(T); 779 if (row[0] != null) 780 model = (T)row[0]; 781 } 782 break; 783 //引用类型 784 case ModelType.Else: 785 { 786 //引用类型 必须对泛型实例化 787 model = Activator.CreateInstance<T>(); 788 //获取model中的属性 789 var modelPropertyInfos = type.GetProperties(); 790 //遍历model每一个属性并赋值DataRow对应的列 791 foreach (var pi in modelPropertyInfos) 792 { 793 //获取属性名称 794 var name = pi.Name; 795 if (!row.Table.Columns.Contains(name) || row[name] == null || row[name] == DBNull.Value) continue; 796 var piType = GetModelType(pi.PropertyType); 797 switch (piType) 798 { 799 case ModelType.Struct: 800 { 801 object value; 802 if (!pi.PropertyType.Name.ToLower().Contains("nullable")) 803 value = Convert.ChangeType(row[name], pi.PropertyType); 804 else 805 value = new NullableConverter(pi.PropertyType).ConvertFromString(row[name].ToString()); 806 pi.SetValue(model, value, null); 807 } 808 break; 809 810 case ModelType.Enum: 811 { 812 var fiType = row[0].GetType(); 813 if (fiType == typeof(int)) 814 { 815 pi.SetValue(model, row[name], null); 816 } 817 else if (fiType == typeof(string)) 818 { 819 var value = (T)Enum.Parse(typeof(T), row[name].ToString()); 820 if (value != null) 821 pi.SetValue(model, value, null); 822 } 823 } 824 break; 825 826 case ModelType.String: 827 { 828 var value = Convert.ChangeType(row[name], pi.PropertyType); 829 pi.SetValue(model, value, null); 830 } 831 break; 832 833 case ModelType.Object: 834 { 835 pi.SetValue(model, row[name], null); 836 } 837 break; 838 839 case ModelType.Else: 840 throw new Exception("不支持该类型转换"); 841 default: 842 throw new Exception("未知类型"); 843 } 844 } 845 } 846 break; 847 848 default: 849 model = default(T); 850 break; 851 } 852 return model; 853 } 854 855 #endregion 856 } 857 #endregion 858 859 #region SqlHelper 860 public class SqlHelper 861 { 862 /// <summary> 863 /// 从配置文件中读取数据库连接字符串 864 /// </summary> 865 public static string ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 866 867 private static SqlConnection conn; 868 869 #region 公共静态方法 870 871 /// <summary> 872 /// 填充DataTable 873 /// </summary> 874 /// <param name="spname">存储过程名</param> 875 /// <param name="sqlParams">参数集</param> 876 /// <returns>结果datatable</returns> 877 public static DataTable FillDataTable(string spname, params SqlParameter[] sqlParams) 878 { 879 conn = new SqlConnection(ConnectionString); 880 using (SqlDataAdapter adapter = new SqlDataAdapter(spname, conn)) 881 { 882 adapter.SelectCommand.CommandType = CommandType.StoredProcedure; 883 if (sqlParams != null && sqlParams.Length > 0) 884 { 885 for (int i = 0; i < sqlParams.Length; i++) 886 { 887 adapter.SelectCommand.Parameters.Add(sqlParams[i]); 888 } 889 } 890 DataTable table = new DataTable(); 891 adapter.Fill(table); 892 return table; 893 } 894 } 895 896 /// <summary> 897 /// 执行一条SQL的select语句,用返回的结果填充DataTable 898 /// </summary> 899 /// <param name="sql">要执行的SQL语句</param> 900 /// <param name="oParams">SQL语句中的参数</param> 901 /// <returns>已填充数据的DataTable</returns> 902 public static DataTable FillSqlDataTable(string sql, params SqlParameter[] oParams) 903 { 904 using (conn = new SqlConnection(ConnectionString)) 905 { 906 SqlDataAdapter adapter = new SqlDataAdapter(sql, conn); 907 if (oParams != null && oParams.Length > 0) 908 { 909 foreach (SqlParameter prm in oParams) 910 { 911 adapter.SelectCommand.Parameters.Add(prm); 912 } 913 } 914 DataTable table = new DataTable(); 915 adapter.Fill(table); 916 return table; 917 } 918 } 919 920 /// <summary> 921 /// 执行一条存储过程,返回SqlDataReader 922 /// </summary> 923 /// <param name="spname">存储过程名称</param> 924 /// <param name="sqlParams">存储过程参数集合</param> 925 /// <returns>SqlDataReader</returns> 926 public static SqlDataReader ExecuteReader(string spname, params SqlParameter[] sqlParams) 927 { 928 return ExecuteReader(CommandType.StoredProcedure, spname, sqlParams); 929 } 930 931 /// <summary> 932 /// 执行一条存储过程或SQL语句,返回SqlDataReader 933 /// </summary> 934 /// <param name="cmdText">SQL语句或存储过程名称</param> 935 /// <param name="sqlParams">SQL参数集合</param> 936 /// <returns>SqlDataReader</returns> 937 public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] sqlParams) 938 { 939 conn = new SqlConnection(ConnectionString); 940 using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 941 { 942 cmd.CommandType = cmdType; 943 if (sqlParams != null && sqlParams.Length > 0) 944 { 945 for (int i = 0; i < sqlParams.Length; i++) 946 { 947 cmd.Parameters.Add(sqlParams[i]); 948 } 949 } 950 try 951 { 952 cmd.Connection.Open(); 953 return cmd.ExecuteReader(CommandBehavior.CloseConnection); 954 } 955 catch 956 { 957 cmd.Connection.Close(); 958 throw; 959 } 960 } 961 } 962 963 /// <summary> 964 /// 执行存储过程 965 /// </summary> 966 /// <param name="spname">存储过程名称</param> 967 /// <param name="sqlParams">存储过程参数集合</param> 968 /// <returns>受影响的记录行数</returns> 969 public static int ExecuteNonQuery(string spname, params SqlParameter[] sqlParams) 970 { 971 return ExecuteNonQuery(CommandType.StoredProcedure, spname, sqlParams); 972 } 973 974 /// <summary> 975 /// 执行一条SQL语句,获取受SQL语句中delete、update和insert语句影响的行数 976 /// </summary> 977 /// <param name="sql">要执行的SQL语句</param> 978 /// <param name="oParams">SQL语句中的参数</param> 979 /// <returns>受SQL语句中delete、update和insert语句影响的行数</returns> 980 public static int ExecuteSqlNonQuery(string sql, params SqlParameter[] oParams) 981 { 982 using (conn = new SqlConnection(ConnectionString)) 983 { 984 SqlCommand cmd = new SqlCommand(sql, conn); 985 conn.Open(); 986 if (oParams != null && oParams.Length > 0) 987 { 988 foreach (SqlParameter prm in oParams) 989 { 990 cmd.Parameters.Add(prm); 991 } 992 } 993 int reslt = cmd.ExecuteNonQuery(); 994 conn.Close(); 995 return reslt; 996 } 997 } 998 999 /// <summary> 1000 /// 执行SQL语句或存储过程 1001 /// </summary> 1002 /// <param name="cmdType">执行类型:SQL语句或存储过程</param> 1003 /// <param name="cmdText">要执行的SQL语句或存储过程名</param> 1004 /// <param name="sqlParams">SQL参数集合</param> 1005 /// <returns>受影响的记录行数</returns> 1006 public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] sqlParams) 1007 { 1008 conn = new SqlConnection(ConnectionString); 1009 1010 using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 1011 { 1012 cmd.CommandType = cmdType; 1013 if (sqlParams != null && sqlParams.Length > 0) 1014 { 1015 for (int i = 0; i < sqlParams.Length; i++) 1016 { 1017 cmd.Parameters.Add(sqlParams[i]); 1018 } 1019 } 1020 conn.Open(); 1021 int j = cmd.ExecuteNonQuery(); 1022 conn.Close(); 1023 return j; 1024 } 1025 } 1026 1027 /// <summary> 1028 /// 执行SQL语句或存储过程返回第一行第一列的数据 1029 /// </summary> 1030 /// <param name="cmdType">执行类型:SQL语句或存储过程</param> 1031 /// <param name="sqlParams">参数集</param> 1032 /// <param name="cmdText">执行语句</param> 1033 /// <returns>返回第一行第一列的数据</returns> 1034 public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] sqlParams) 1035 { 1036 conn = new SqlConnection(ConnectionString); 1037 using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 1038 { 1039 cmd.CommandType = cmdType; 1040 if (sqlParams != null && sqlParams.Length > 0) 1041 { 1042 for (int i = 0; i < sqlParams.Length; i++) 1043 { 1044 cmd.Parameters.Add(sqlParams[i]); 1045 } 1046 } 1047 conn.Open(); 1048 object obj = null; 1049 try 1050 { 1051 obj = cmd.ExecuteScalar(); 1052 } 1053 catch 1054 { 1055 conn.Close(); 1056 conn.Open(); 1057 obj = cmd.ExecuteScalar(); 1058 } 1059 conn.Close(); 1060 return obj; 1061 } 1062 } 1063 1064 /// <summary> 1065 /// 执行存储过程,填充DataRow,若无数据则返回null 1066 /// </summary> 1067 /// <param name="spname">执行语句</param> 1068 /// <param name="sqlParams">参数集</param> 1069 /// <returns>返回DataRow</returns> 1070 public static DataRow FillDataRow(string spname, params SqlParameter[] sqlParams) 1071 { 1072 DataTable table = FillDataTable(spname, sqlParams); 1073 if (table.Rows.Count > 0) 1074 return table.Rows[0]; 1075 return null; 1076 } 1077 1078 /// <summary> 1079 /// 向数据库中插入或更新数据时,设置存储过程参数 1080 /// </summary> 1081 /// <param name="pName">存储过程参数名</param> 1082 /// <param name="pValue">参数值</param> 1083 /// <returns>返回SqlParameter</returns> 1084 public static SqlParameter SetParam(string pName, object pValue) 1085 { 1086 //如果pValue为null,则直接返回 2004-12-6 1087 if (pValue == null) 1088 return new SqlParameter(pName, pValue); 1089 switch (Type.GetTypeCode(pValue.GetType())) 1090 { 1091 case TypeCode.String: 1092 string tempStr = (string)pValue; 1093 if (tempStr.Equals(null) || tempStr.Trim().Length.Equals(0)) 1094 { 1095 return new SqlParameter(pName, DBNull.Value); 1096 } 1097 return new SqlParameter(pName, tempStr); 1098 1099 case TypeCode.DateTime: 1100 DateTime tempdt = (DateTime)pValue; 1101 if (tempdt.Equals(DateTime.MinValue)) 1102 { 1103 return new SqlParameter(pName, DBNull.Value); 1104 } 1105 return new SqlParameter(pName, tempdt); 1106 1107 default: 1108 return new SqlParameter(pName, pValue); 1109 } 1110 } 1111 1112 /// <summary> 1113 /// 获取SqlDataReader中指定字符串字段的值 1114 /// </summary> 1115 /// <param name="reader">包含数据的SqlDataReader</param> 1116 /// <param name="fieldName">字段名</param> 1117 /// <returns>字段值,若字段为空则返回空字符串</returns> 1118 public static string GetStringFieldValue(SqlDataReader reader, string fieldName) 1119 { 1120 if (Convert.IsDBNull(reader[fieldName])) 1121 { 1122 return String.Empty; 1123 } 1124 return reader[fieldName].ToString(); 1125 } 1126 1127 /// <summary> 1128 /// 获取SqlDataReader中指定Int字段的值,若该字段为空则返回指定的替换值 1129 /// </summary> 1130 /// <param name="reader">包含数据的SqlDataReader</param> 1131 /// <param name="fieldName">字段名</param> 1132 /// <param name="replaceValue">要替换值为空的字段的值</param> 1133 /// <returns>字段值,若该字段为空则返回replaceValue</returns> 1134 public static int GetIntFieldValue(SqlDataReader reader, string fieldName, int replaceValue) 1135 { 1136 if (Convert.IsDBNull(reader[fieldName])) 1137 { 1138 return replaceValue; 1139 } 1140 object obj = reader[fieldName]; 1141 return Convert.ToInt32(reader[fieldName]); 1142 } 1143 1144 /// <summary> 1145 /// 获取SqlDataReader中指定Int字段的值 1146 /// </summary> 1147 /// <param name="reader">包含数据的SqlDataReader</param> 1148 /// <param name="fieldName">字段名</param> 1149 /// <returns>字段值,若该字段为空则返回0</returns> 1150 public static int GetIntFieldValue(SqlDataReader reader, string fieldName) 1151 { 1152 return GetIntFieldValue(reader, fieldName, 0); 1153 } 1154 1155 /// <summary> 1156 /// 获取SqlDataReader中指定byte字段(SQL Server中为tinyint类型)的值 1157 /// </summary> 1158 /// <param name="reader">包含数据的SqlDataReader</param> 1159 /// <param name="fieldName">要取值的字段名</param> 1160 /// <returns>返回byte类型结果</returns> 1161 public static byte GetByteFieldValue(SqlDataReader reader, string fieldName) 1162 { 1163 if (Convert.IsDBNull(reader[fieldName])) 1164 return 0; 1165 return (byte)reader[fieldName]; 1166 } 1167 1168 /// <summary> 1169 /// 获取SqlDataReader中指定decimal字段的值,若该字段为空则返回指定的替换值 1170 /// </summary> 1171 /// <param name="reader">包含数据的SqlDataReader</param> 1172 /// <param name="fieldName">要取值的字段名</param> 1173 /// <param name="replaceValue">要替换值为空的字段的值</param> 1174 /// <returns>返回double类型结果</returns> 1175 public static Double GetDoubleFieldValue(SqlDataReader reader, string fieldName, Double replaceValue) 1176 { 1177 if (Convert.IsDBNull(reader[fieldName])) 1178 return replaceValue; 1179 return (Double)reader[fieldName]; 1180 } 1181 1182 /// <summary> 1183 /// 获取SqlDataReader中指定Int字段的值,若该字段为空则返回0 1184 /// </summary> 1185 /// <param name="reader">包含数据的SqlDataReader</param> 1186 /// <param name="fieldName">要取值的字段名</param> 1187 /// <returns>返回double类型结果</returns> 1188 public static Double GetDoubleFieldValue(SqlDataReader reader, string fieldName) 1189 { 1190 return GetDoubleFieldValue(reader, fieldName, 0); 1191 } 1192 1193 /// <summary> 1194 /// 获取SqlDataReader中指定float字段的值,若该字段为空则返回0 1195 /// </summary> 1196 /// <param name="reader">包含数据的SqlDataReader</param> 1197 /// <param name="fieldName">要取值的字段名</param> 1198 /// <returns>返回double类型结果</returns> 1199 public static float GetFloatFieldValue(SqlDataReader reader, string fieldName) 1200 { 1201 return GetFloatFieldValue(reader, fieldName, 0); 1202 } 1203 1204 /// <summary> 1205 /// 获取SqlDataReader中指定decimal字段的值,若该字段为空则返回指定的替换值 1206 /// </summary> 1207 /// <param name="reader">包含数据的SqlDataReader</param> 1208 /// <param name="fieldName">要取值的字段名</param> 1209 /// <param name="replaceValue">要替换值为空的字段的值</param> 1210 /// <returns>返回double类型结果</returns> 1211 public static float GetFloatFieldValue(SqlDataReader reader, string fieldName, float replaceValue) 1212 { 1213 if (Convert.IsDBNull(reader[fieldName])) 1214 return replaceValue; 1215 return float.Parse(reader[fieldName].ToString()); 1216 } 1217 1218 /// <summary> 1219 /// 获取SqlDataReader中指定Int字段的值,若该字段为空则返回DateTime的最小值 1220 /// </summary> 1221 /// <param name="reader">包含数据的SqlDataReader</param> 1222 /// <param name="fieldName">要取值的字段名</param> 1223 /// <returns>返回DateTime类型结果</returns> 1224 public static DateTime GetDateTimeFieldValue(SqlDataReader reader, string fieldName) 1225 { 1226 if (Convert.IsDBNull(reader[fieldName])) 1227 return DateTime.MinValue; 1228 return (DateTime)reader[fieldName]; 1229 } 1230 1231 #region 仅用于综合查询 1232 1233 /// <summary> 1234 /// 执行查询语句,返回DataSet(zhaibl 09-11-04添加此方法) 1235 /// </summary> 1236 /// <param name="SQLString">查询语句</param> 1237 /// <returns>DataSet</returns> 1238 public static DataSet Query(string SQLString) 1239 { 1240 using (SqlConnection connection = new SqlConnection(ConnectionString)) 1241 { 1242 DataSet ds = new DataSet(); 1243 try 1244 { 1245 connection.Open(); 1246 SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); 1247 command.Fill(ds, "ds"); 1248 } 1249 catch (System.Data.SqlClient.SqlException ex) 1250 { 1251 throw new Exception(ex.Message); 1252 } 1253 return ds; 1254 } 1255 } 1256 1257 /// <summary> 1258 /// 执行一条计算查询结果语句,返回查询结果(object)。 1259 /// </summary> 1260 /// <param name="SQLString">计算查询结果语句</param> 1261 /// <returns>查询结果(object)</returns> 1262 public static object GetSingle(string SQLString) 1263 { 1264 using (SqlConnection connection = new SqlConnection(ConnectionString)) 1265 { 1266 using (SqlCommand cmd = new SqlCommand(SQLString, connection)) 1267 { 1268 try 1269 { 1270 connection.Open(); 1271 object obj = cmd.ExecuteScalar(); 1272 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 1273 { 1274 return null; 1275 } 1276 else 1277 { 1278 return obj; 1279 } 1280 } 1281 catch (System.Data.SqlClient.SqlException e) 1282 { 1283 connection.Close(); 1284 throw new Exception(e.Message); 1285 } 1286 } 1287 } 1288 } 1289 1290 /// <summary> 1291 /// 填充数据集(执行带参的sql),返回DataSet 1292 /// </summary> 1293 /// <param name="sql">sql语句</param> 1294 /// <param name="oParams">参数集</param> 1295 /// <returns>datasat</returns> 1296 public static DataSet FillDataSet(string sql, params SqlParameter[] oParams) 1297 { 1298 using (SqlConnection conn = new SqlConnection(ConnectionString)) 1299 { 1300 SqlDataAdapter adapter = new SqlDataAdapter(sql, conn); 1301 if (oParams != null && oParams.Length > 0) 1302 { 1303 foreach (SqlParameter prm in oParams) 1304 { 1305 adapter.SelectCommand.Parameters.Add(prm); 1306 } 1307 } 1308 DataSet ds = new DataSet(); 1309 adapter.Fill(ds); 1310 return ds; 1311 } 1312 } 1313 1314 /// <summary> 1315 /// 执行一条SQL语句,获取受SQL语句中delete、update和insert语句影响的行数 1316 /// </summary> 1317 /// <param name="sql">要执行的SQL语句</param> 1318 /// <param name="oParams">SQL语句中的参数</param> 1319 /// <returns>受SQL语句中delete、update和insert语句影响的行数</returns> 1320 public static int ExecuteSqlNonQuery1(string sql, params SqlParameter[] oParams) 1321 { 1322 int reslt = 0; 1323 try 1324 { 1325 using (conn = new SqlConnection(ConnectionString)) 1326 { 1327 SqlCommand cmd = new SqlCommand(sql, conn); 1328 conn.Open(); 1329 cmd.CommandType = CommandType.StoredProcedure; 1330 cmd.Parameters.AddRange(oParams); 1331 reslt = cmd.ExecuteNonQuery(); 1332 conn.Close(); 1333 } 1334 } 1335 catch (Exception e) 1336 { 1337 throw new Exception(e.Message); 1338 } 1339 return reslt; 1340 } 1341 1342 /// <summary> 1343 /// 获取查询结果 1344 /// </summary> 1345 /// <param name="sql">要执行的SQL语句</param> 1346 /// <returns>DataTable</returns> 1347 public static DataTable GetQueryResult(string sql) 1348 { 1349 DataTable tbl = new DataTable(); 1350 conn = new SqlConnection(ConnectionString); 1351 using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conn)) 1352 { 1353 adapter.Fill(tbl); 1354 } 1355 conn.Close(); 1356 return tbl; 1357 } 1358 1359 #endregion 仅用于综合查询 1360 1361 #endregion 公共静态方法 1362 1363 #region 事务--Bao--2017-08-17 1364 1365 /// <summary> 1366 /// 创建一个事务 1367 /// </summary> 1368 /// <returns></returns> 1369 public static SqlTransaction CreateTrans() 1370 { 1371 conn = new SqlConnection(ConnectionString); 1372 conn.Open(); 1373 return conn.BeginTransaction(); 1374 } 1375 1376 /// <summary> 1377 /// 关闭并释放与事务有关的资源 1378 /// </summary> 1379 /// <param name="trans"></param> 1380 public static void CloseTrans(SqlTransaction trans) 1381 { 1382 if (trans == null) return; 1383 1384 trans.Dispose(); 1385 1386 if (conn == null || conn.State != ConnectionState.Open) return; 1387 conn.Close(); 1388 conn.Dispose(); 1389 } 1390 1391 /// <summary> 1392 /// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事物处理 1393 /// 使用参数数组提供参数 1394 /// </summary> 1395 /// <param name="trans">一个存在的 sql 事物处理</param> 1396 /// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param> 1397 /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param> 1398 /// <param name="sqlParams">以数组形式提供SqlCommand命令中用到的参数列表</param> 1399 /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns> 1400 public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] sqlParams) 1401 { 1402 if (trans == null) return ExecuteNonQuery(cmdType, cmdText, sqlParams); 1403 1404 using (SqlCommand cmd = new SqlCommand()) 1405 { 1406 PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, sqlParams); 1407 int val = cmd.ExecuteNonQuery(); 1408 cmd.Parameters.Clear(); 1409 return val; 1410 } 1411 } 1412 1413 /// <summary> 1414 /// 执行SQL语句或存储过程返回第一行第一列的数据 1415 /// </summary> 1416 /// <param name="trans">一个存在的 sql 事物处理</param> 1417 /// <param name="cmdType">执行类型:SQL语句或存储过程</param> 1418 /// <param name="sqlParams">参数集</param> 1419 /// <param name="cmdText">执行语句</param> 1420 /// <returns>返回第一行第一列的数据</returns> 1421 public static object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] sqlParams) 1422 { 1423 if (trans == null) return ExecuteScalar(cmdType, cmdText, sqlParams); 1424 1425 using (SqlCommand cmd = new SqlCommand()) 1426 { 1427 PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, sqlParams); 1428 object val = cmd.ExecuteScalar(); 1429 cmd.Parameters.Clear(); 1430 return val; 1431 } 1432 } 1433 1434 /// <summary> 1435 /// 为执行命令准备参数 1436 /// </summary> 1437 /// <param name="cmd">SqlCommand 命令</param> 1438 /// <param name="conn">已经存在的数据库连接</param> 1439 /// <param name="trans">数据库事物处理</param> 1440 /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param> 1441 /// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param> 1442 /// <param name="cmdParms">返回带参数的命令</param> 1443 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) 1444 { 1445 //判断数据库连接状态 1446 if (conn.State != ConnectionState.Open) 1447 conn.Open(); 1448 1449 cmd.Connection = conn; 1450 cmd.CommandText = cmdText; 1451 1452 //判断是否需要事物处理 1453 if (trans != null) 1454 cmd.Transaction = trans; 1455 1456 cmd.CommandType = cmdType; 1457 1458 if (cmdParms != null) 1459 { 1460 foreach (SqlParameter parm in cmdParms) 1461 cmd.Parameters.Add(parm); 1462 } 1463 } 1464 1465 #endregion 事务--Bao--2017-08-17 1466 1467 public static void LogInfo(string msg) 1468 { 1469 string FilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log\\"; 1470 if (!System.IO.Directory.Exists(FilePath)) 1471 { 1472 System.IO.Directory.CreateDirectory(FilePath); 1473 } 1474 try 1475 { 1476 string fileName = FilePath + DateTime.Now.ToString("yyyyMMdd") + ".log"; 1477 var logStreamWriter = new System.IO.StreamWriter(fileName, true, Encoding.GetEncoding("gb2312")); 1478 1479 1480 logStreamWriter.WriteLine(msg); 1481 logStreamWriter.Close(); 1482 } 1483 catch 1484 { } 1485 } 1486 1487 #region 标准MD5加密 1488 /// <summary> 1489 /// MD5加密字符串 1490 /// </summary> 1491 /// <param name="str"></param> 1492 /// <returns></returns> 1493 public static string Md5String(string str) 1494 { 1495 string pwd = String.Empty; 1496 MD5 md5 = MD5.Create(); 1497 // 编码UTF8/Unicode 1498 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); 1499 // 转换成字符串 1500 for (int i = 0; i < s.Length; i++) 1501 { 1502 //格式后的字符是小写的字母 1503 //如果使用大写(X)则格式后的字符是大写字符 1504 pwd = pwd + s[i].ToString("x2"); 1505 } 1506 return pwd; 1507 } 1508 #endregion 1509 1510 #region 分页 1511 1512 /// <summary> 1513 /// 获取分页数据 1514 /// </summary> 1515 /// <param name="tableName">表名</param> 1516 /// <param name="primaryKey">主键字段名</param> 1517 /// <param name="pageIndex">页码</param> 1518 /// <param name="pageSize">页尺寸</param> 1519 /// <param name="isReCount">返回记录总数, 非 0 值则返回</param> 1520 /// <param name="orderType">设置排序类型, 非 0 值则降序</param> 1521 /// <param name="where">查询条件 (注意: 不要加 where)</param> 1522 /// <param name="recount">返回记录总数</param> 1523 /// <param name="pageCount">返回总页数</param> 1524 /// <returns></returns> 1525 public static DataTable GetPage(string tableName, string primaryKey, int pageIndex, int pageSize, int isReCount, int orderType, string where, out int recount, out int pageCount) 1526 { 1527 string procName = "SP_Page"; 1528 SqlParameter[] paras = new SqlParameter[]{ 1529 new SqlParameter("@Recount",SqlDbType.Int), 1530 new SqlParameter("@PageCount",SqlDbType.Int), 1531 new SqlParameter("@tblName",tableName), 1532 new SqlParameter("@fldName",primaryKey), 1533 new SqlParameter("@PageSize",pageSize), 1534 new SqlParameter("@PageIndex",pageIndex), 1535 new SqlParameter("@IsReCount",isReCount), 1536 new SqlParameter("@OrderType",orderType), 1537 new SqlParameter("@strWhere",where) 1538 }; 1539 1540 paras[0].Direction = ParameterDirection.Output; 1541 paras[1].Direction = ParameterDirection.Output; 1542 1543 DataTable dt = SqlHelper.FillDataTable(procName, paras); 1544 1545 recount = int.Parse(paras[0].Value.ToString()); 1546 pageCount = int.Parse(paras[1].Value.ToString()); 1547 1548 return dt; 1549 } 1550 1551 1552 1553 1554 1555 1556 public static string newShowPageNavNew(int pageCurrent, int totalCount, int pageSize = 5, string methodName = "getlist") 1557 { 1558 var totalPage = Math.Max((totalCount + pageSize - 1) / pageSize, 1); 1559 //if (totalPage >= 1) 1560 //{ 1561 //要输出的超链接字符串 1562 var pageNav = new StringBuilder(); 1563 //左边代码 1564 //无数据 1565 if (totalCount == 0) 1566 { 1567 pageNav.AppendFormat("<div class='col-sm-4'><div class='dataTables_info' id='editable_info' role='alert' aria-live='polite' aria-relevant='all'>显示 0 项,共 0 项</div></div>"); 1568 } 1569 else 1570 { 1571 //最后一页文件数量 1572 if (pageCurrent == totalPage) 1573 { 1574 pageNav.AppendFormat("<div class='col-sm-4'><div class='dataTables_info' id='editable_info' role='alert' aria-live='polite' aria-relevant='all'>显示 " + ((pageCurrent - 1) * pageSize + 1) + " 到 " + totalCount + " 项,共 " + totalCount + " 项</div></div>"); 1575 } 1576 else 1577 { 1578 pageNav.AppendFormat("<div class='col-sm-4'><div class='dataTables_info' id='editable_info' role='alert' aria-live='polite' aria-relevant='all'>显示 " + ((pageCurrent - 1) * pageSize + 1) + " 到 " + (pageCurrent * pageSize) + " 项,共 " + totalCount + " 项</div></div>"); 1579 } 1580 } 1581 1582 //右边代码 1583 pageNav.AppendFormat("<div class='col-sm-8'><div class='dataTables_paginate paging_simple_numbers' id='editable_paginate'><ul class='pagination'>"); 1584 1585 //如果当前是第一页,则“上一页”不可点 1586 if (pageCurrent == 1) 1587 { 1588 pageNav.AppendFormat("<li class='paginate_button previous disabled' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)'>上一页</a></li>"); 1589 } 1590 else 1591 { 1592 pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", pageCurrent - 1, pageSize, "上一页"); 1593 } 1594 1595 //中间页码 1596 if (pageCurrent <= 3) 1597 { 1598 for (int i = 1; i < 8; i++) 1599 { 1600 if (i <= totalPage) 1601 { 1602 if (pageCurrent == i) //当前页处理 1603 { 1604 pageNav.AppendFormat("<li class='paginate_button active' aria-controls='editable' tabindex='0'><a href='javascript:void(0)'>{0}</a></li>", pageCurrent); 1605 } 1606 else //一般页处理 1607 { 1608 pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", i, pageSize, i); 1609 } 1610 } 1611 } 1612 } 1613 else if (pageCurrent > 3 && pageCurrent < totalPage - 3) 1614 { 1615 int current = 4; 1616 for (int i = 1; i < 8; i++) 1617 { 1618 if ((pageCurrent + i - current) >= 1 && (pageCurrent + i - current) <= totalPage) 1619 { 1620 if (current == i) //当前页处理 1621 { 1622 pageNav.AppendFormat("<li class='paginate_button active' aria-controls='editable' tabindex='0'><a href='javascript:void(0)'>{0}</a></li>", pageCurrent); 1623 } 1624 else //一般页处理 1625 { 1626 pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", pageCurrent + i - current, pageSize, pageCurrent + i - current); 1627 } 1628 } 1629 } 1630 1631 } 1632 else 1633 { 1634 for (int i = totalPage - 6; i <= totalPage; i++) 1635 { 1636 if (i <= totalPage && i > 0) 1637 { 1638 if (pageCurrent == i) //当前页处理 1639 { 1640 pageNav.AppendFormat("<li class='paginate_button active' aria-controls='editable' tabindex='0'><a href='javascript:void(0)'>{0}</a></li>", pageCurrent); 1641 } 1642 else //一般页处理 1643 { 1644 pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", i, pageSize, i); 1645 } 1646 } 1647 } 1648 } 1649 1650 //如果当前是最后一页,则“下一页”不可点 1651 if (pageCurrent == totalPage) 1652 { 1653 pageNav.AppendFormat("<li class='paginate_button next disabled' aria-controls='editable' tabindex='0' id='editable_next'><a href='javascript:void(0)'>下一页</a></li>"); 1654 } 1655 else 1656 { 1657 pageNav.AppendFormat("<li class='paginate_button next' aria-controls='editable' tabindex='0' id='editable_next'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", pageCurrent + 1, pageSize, "下一页"); 1658 } 1659 pageNav.AppendFormat("</ul></div></div>"); 1660 return pageNav.ToString(); 1661 //} 1662 //else 1663 //{ 1664 // return string.Empty; 1665 //} 1666 } 1667 #endregion 1668 } 1669 #endregion 1670 }