码迷,mamicode.com
首页 > 数据库 > 详细

Db - DataAccess

时间:2017-07-01 10:01:10      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:rollback   into   rtp   nstat   scalar   case   连接字符串   开始   reader   

   1 /* Jonney Create 2013-8-12 */
   2 
   3 /*using System.Data.OracleClient;*/
   4 /*using System.Data.SQLite;*/
   5 /*using MySql.Data.MySqlClient;*/
   6 using System.Data.SqlClient;
   7 using System;
   8 using System.Collections.Generic;
   9 using System.ComponentModel;
  10 using System.Data;
  11 using System.Reflection;
  12 
  13 namespace Dade.DataCenter.CutBoard.Dal
  14 {
  15     public class SqlDataAccess : DataAccess
  16     {
  17         protected SqlDataAccess()
  18         {
  19             _databaseType = DatabaseType.SqlServer;
  20             _connString = ConnStr;
  21             _conn = new SqlConnection(_connString);
  22             _cmd = _conn.CreateCommand();
  23             _dataAdapter = new SqlDataAdapter();
  24             _dataAdapter.SelectCommand = _cmd;
  25         }
  26 
  27         public static string ConnStr { get; set; }
  28 
  29         public static DataAccess Instance
  30         {
  31             get { return new SqlDataAccess(); }
  32         }
  33     }
  34 
  35     public class OracleDataAccess : DataAccess
  36     {
  37         protected OracleDataAccess()
  38         {
  39             /*_databaseType = DatabaseType.Oracle;
  40             _connString = ConnStr;
  41             _conn = new OracleConnection(_connString);
  42             _cmd = _conn.CreateCommand();
  43             _dataAdapter = new OracleDataAdapter();
  44             _dataAdapter.SelectCommand = _cmd;
  45             _parameterChar = ":";*/
  46         }
  47 
  48         public static string ConnStr { get; set; }
  49         public static DataAccess Instance
  50         {
  51             get { return new OracleDataAccess(); }
  52         }
  53     }
  54 
  55     public class SqliteDataAccess : DataAccess
  56     {
  57         protected SqliteDataAccess()
  58         {
  59             /*_databaseType = DatabaseType.Sqlite;
  60             _connString = ConnStr;
  61             _conn = new SQLiteConnection(_connString);
  62             _cmd = _conn.CreateCommand();
  63             _dataAdapter = new SQLiteDataAdapter();
  64             _dataAdapter.SelectCommand = _cmd;*/
  65         }
  66 
  67         public static string ConnStr { get; set; }
  68         public static DataAccess Instance
  69         {
  70             get { return new SqliteDataAccess(); }
  71         }
  72     }
  73 
  74     public class MySqlDataAccess : DataAccess
  75     {
  76         protected MySqlDataAccess()
  77         {
  78             /*_databaseType = DatabaseType.Mysql;
  79             _connString = ConnStr;
  80             _conn = new MySqlConnection(_connString);
  81             _cmd = _conn.CreateCommand();
  82             _dataAdapter = new MySqlDataAdapter();
  83             _dataAdapter.SelectCommand = _cmd;*/
  84         }
  85 
  86         public static string ConnStr { get; set; }
  87         public static DataAccess Instance
  88         {
  89             get { return new MySqlDataAccess(); }
  90         }
  91 
  92     }
  93 
  94     /// <summary>
  95     /// 数据库类型
  96     /// </summary>
  97     public enum DatabaseType
  98     {
  99         SqlServer, Oracle, Mysql, Sqlite, PostgreSql, SqlCe, Access, Firebird
 100     }
 101 
 102     /// <summary>
 103     /// 通用数据库访问抽象类
 104     /// </summary>
 105     public abstract class DataAccess : IDisposable
 106     {
 107         protected DatabaseType _databaseType;
 108         protected string _connString;
 109         protected bool _useTransaction;
 110         protected IDbConnection _conn;
 111         protected IDbTransaction _transaction;
 112         protected IDbCommand _cmd;
 113         protected IDbDataAdapter _dataAdapter;
 114         protected string _parameterChar = "@";
 115 
 116         /// <summary>
 117         /// 根据数据库类型返回参数
 118         /// </summary>
 119         /// <param name="parameterName"></param>
 120         /// <param name="value"></param>
 121         /// <returns></returns>
 122         public IDbDataParameter GetParameter(string parameterName, object value)
 123         {
 124             try
 125             {
 126                 IDbDataParameter parameter = null;
 127                 switch (_databaseType)
 128                 {
 129                     case DatabaseType.SqlServer:
 130                         parameter = new SqlParameter(parameterName, value ?? DBNull.Value);
 131                         break;
 132                     /*case DatabaseType.Mysql:
 133                         parameter = new MySqlParameter(parameterName, value ?? DBNull.Value);
 134                         break;*/
 135                     /*case DatabaseType.Oracle:
 136                         parameter = new OracleParameter(parameterName, value ?? DBNull.Value);
 137                         break;*/
 138                     /*case DatabaseType.Sqlite:
 139                         parameter = new SQLiteParameter(parameterName, value ?? DBNull.Value);
 140                         break;*/
 141                     default:
 142                         throw new Exception("DataAccess-->DatabaseType-->GetParameter()-->Not Implement");
 143                 }
 144                 return parameter;
 145             }
 146             catch
 147             {
 148                 DoCatch();
 149                 throw;
 150             }
 151         }
 152 
 153         /// <summary>
 154         /// 异常处理
 155         /// </summary>
 156         protected void DoCatch()
 157         {
 158             if (_useTransaction && _transaction!=null && _transaction.Connection !=null)
 159             {
 160                 _transaction.Rollback();
 161                 _transaction.Dispose();
 162                 _transaction = null;
 163                 _useTransaction = false;
 164             }
 165             Close();
 166         }
 167 
 168         /// <summary>
 169         /// 获取是否使用事务
 170         /// </summary>
 171         public bool UseTransaction
 172         {
 173             get { return _useTransaction; }
 174         }
 175 
 176         /// <summary>
 177         /// 获取当前正在执行的事务
 178         /// </summary>
 179         public IDbTransaction Transaction
 180         {
 181             get { return _transaction; }
 182         }
 183 
 184         /// <summary>
 185         /// 获取或设置连接字符串
 186         /// </summary>
 187         public string ConnString
 188         {
 189             get { return _connString; }
 190             set
 191             {
 192                 _connString = value;
 193                 if (_conn != null && _conn.ConnectionString != value)
 194                 {
 195                     _conn.ConnectionString = _connString;
 196                 }
 197             }
 198         }
 199 
 200         /// <summary>
 201         /// Ping服务器IP
 202         /// </summary>
 203         /// <param name="ip">目标主机IP</param>
 204         /// <returns></returns>
 205         public static bool Ping(string ip)
 206         {
 207             try
 208             {
 209                 var p = new System.Net.NetworkInformation.Ping();
 210                 var options = new System.Net.NetworkInformation.PingOptions { DontFragment = true };
 211                 byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Ping..");
 212                 const int timeout = 1000; // Timeout 时间,单位:毫秒
 213                 System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
 214                 return reply != null && reply.Status == System.Net.NetworkInformation.IPStatus.Success;
 215             }
 216             catch
 217             {
 218                 return false;
 219             }
 220         }
 221 
 222         /// <summary>
 223         /// 测试连接字符串
 224         /// </summary>
 225         /// <returns></returns>
 226         public bool TestConnect()
 227         {
 228             try
 229             {
 230                 Open();
 231                 Close();
 232                 return true;
 233             }
 234             catch
 235             {
 236                 DoCatch();
 237                 return false;
 238             }
 239         }
 240 
 241         /// <summary>
 242         /// 是否存在
 243         /// </summary>
 244         /// <param name="sql"></param>
 245         /// <param name="parameters"></param>
 246         /// <returns></returns>
 247         public bool Exists(string sql, params IDbDataParameter[] parameters)
 248         {
 249             var result = GetSingle(sql, parameters);
 250             if (result!=null && result!=DBNull.Value && result.ToString()!="0")
 251             {
 252                 return true;
 253             }
 254             return false;
 255         }
 256 
 257         /// <summary>
 258         /// 查询
 259         /// </summary>
 260         /// <param name="sql">查询语句</param>
 261         /// <returns></returns>
 262         public DataSet Query(string sql)
 263         {
 264             try
 265             {
 266                 DataSet ds = new DataSet();
 267                 _cmd.Connection = _conn;
 268                 _cmd.CommandType = CommandType.Text;
 269                 _cmd.CommandText = sql;
 270                 _cmd.Parameters.Clear();
 271                 _dataAdapter.SelectCommand = _cmd;
 272 
 273                 if (_useTransaction)
 274                 {
 275                     _dataAdapter.Fill(ds);
 276                 }
 277                 else
 278                 {
 279                     Open();
 280                     _dataAdapter.Fill(ds);
 281                     Close();
 282                 }
 283                 return ds;
 284             }
 285             catch
 286             {
 287                 DoCatch();
 288                 throw;
 289             }
 290         }
 291         
 292         /// <summary>
 293         /// 查询
 294         /// </summary>
 295         /// <param name="type">参数类型</param>
 296         /// <param name="sql">查询语句</param>
 297         /// <param name="parameters">参数列表</param>
 298         /// <returns></returns>
 299         public DataSet Query(CommandType type, string sql, params IDbDataParameter[] parameters)
 300         {
 301             try
 302             {
 303                 DataSet ds = new DataSet();
 304                 _cmd.Connection = _conn;
 305                 _cmd.CommandType = type;
 306                 _cmd.CommandText = sql;
 307                 _dataAdapter.SelectCommand = _cmd;
 308                 ReSetParameters(_cmd, parameters);
 309                 if (_useTransaction)
 310                 {
 311                     _dataAdapter.Fill(ds);
 312                 }
 313                 else
 314                 {
 315                     Open();
 316                     _dataAdapter.Fill(ds);
 317                     Close();
 318                 }
 319                 return ds;
 320             }
 321             catch
 322             {
 323                 DoCatch();
 324                 throw;
 325             }
 326         }
 327 
 328         /// <summary>
 329         /// 查询
 330         /// </summary>
 331         /// <param name="sql">查询语句</param>
 332         /// <param name="parameters">参数列表</param>
 333         /// <returns></returns>
 334         public DataSet Query(string sql, params IDbDataParameter[] parameters)
 335         {
 336             try
 337             {
 338                 DataSet ds = new DataSet();
 339                 _cmd.Connection = _conn;
 340                 _cmd.CommandType = CommandType.Text;
 341                 _cmd.CommandText = sql;
 342                 _dataAdapter.SelectCommand = _cmd;
 343                 ReSetParameters(_cmd, parameters);
 344                 if (_useTransaction)
 345                 {
 346                     _dataAdapter.Fill(ds);
 347                 }
 348                 else
 349                 {
 350                     Open();
 351                     _dataAdapter.Fill(ds);
 352                     Close();
 353                 }
 354                 return ds;
 355             }
 356             catch
 357             {
 358                 DoCatch();
 359                 throw;
 360             }
 361         }
 362 
 363         /// <summary>
 364         /// 返回T类型的实体
 365         /// </summary>
 366         /// <typeparam name="T"></typeparam>
 367         /// <param name="sql"></param>
 368         /// <param name="parameters"></param>
 369         /// <returns></returns>
 370         public T QuerySingle<T>(string sql, params IDbDataParameter[] parameters)
 371         {
 372             try
 373             {
 374                 DataSet ds = new DataSet();
 375                 _cmd.Connection = _conn;
 376                 _cmd.CommandType = CommandType.Text;
 377                 _cmd.CommandText = sql;
 378                 _dataAdapter.SelectCommand = _cmd;
 379                 ReSetParameters(_cmd, parameters);
 380                 if (_useTransaction)
 381                 {
 382                     _dataAdapter.Fill(ds);
 383                 }
 384                 else
 385                 {
 386                     Open();
 387                     _dataAdapter.Fill(ds);
 388                     Close();
 389                 }
 390                 if (ds.Tables.Count>0 && ds.Tables[0].Rows.Count>0)
 391                 {
 392                     return ds.Tables[0].Rows[0].ToEntity<T>();
 393                 }
 394                 return default(T);
 395             }
 396             catch
 397             {
 398                 DoCatch();
 399                 throw;
 400             }
 401         }
 402 
 403         /// <summary>
 404         /// 查询实体集合
 405         /// </summary>
 406         /// <typeparam name="T"></typeparam>
 407         /// <param name="sql"></param>
 408         /// <param name="parameters"></param>
 409         /// <returns></returns>
 410         public List<T> Query<T>(string sql, params IDbDataParameter[] parameters)
 411         {
 412             try
 413             {
 414                 DataSet ds = new DataSet();
 415                 _cmd.Connection = _conn;
 416                 _cmd.CommandType = CommandType.Text;
 417                 _cmd.CommandText = sql;
 418                 _dataAdapter.SelectCommand = _cmd;
 419                 ReSetParameters(_cmd, parameters);
 420                 if (_useTransaction)
 421                 {
 422                     _dataAdapter.Fill(ds);
 423                 }
 424                 else
 425                 {
 426                     Open();
 427                     _dataAdapter.Fill(ds);
 428                     Close();
 429                 }
 430                 if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
 431                 {
 432                     return ds.Tables[0].ToList<T>();
 433                 }
 434                 return null;
 435             }
 436             catch
 437             {
 438                 DoCatch();
 439                 throw;
 440             }
 441         }
 442 
 443         /// <summary>
 444         /// 查询
 445         /// </summary>
 446         /// <param name="cmd">IDbCommand</param>
 447         /// <param name="parameters">参数列表</param>
 448         /// <returns></returns>
 449         public DataSet Query(IDbCommand cmd, params IDbDataParameter[] parameters)
 450         {
 451             try
 452             {
 453                 DataSet ds = new DataSet();
 454                 cmd.Connection = _conn;
 455                 _dataAdapter.SelectCommand = cmd;
 456                 ReSetParameters(cmd, parameters);
 457                 if (_useTransaction)
 458                 {
 459                     _dataAdapter.Fill(ds);
 460                 }
 461                 else
 462                 {
 463                     Open();
 464                     _dataAdapter.Fill(ds);
 465                     Close();
 466                 }
 467                 return ds;
 468             }
 469             catch
 470             {
 471                 DoCatch();
 472                 throw;
 473             }
 474         }
 475 
 476         /// <summary>
 477         /// 执行sql
 478         /// </summary>
 479         /// <param name="sql"></param>
 480         /// <returns></returns>
 481         public int ExecuteSql(string sql)
 482         {
 483             try
 484             {
 485                 int result;
 486                 _cmd.CommandType = CommandType.Text;
 487                 _cmd.CommandText = sql;
 488                 _cmd.Connection = _conn;
 489                 _cmd.Parameters.Clear();
 490 
 491                 if (_useTransaction)
 492                 {
 493                     result = _cmd.ExecuteNonQuery();
 494                 }
 495                 else
 496                 {
 497                     Open();
 498                     result = _cmd.ExecuteNonQuery();
 499                     Close();
 500                 }
 501                 return result;
 502             }
 503             catch
 504             {
 505                 DoCatch();
 506                 throw;
 507             }
 508         }
 509 
 510         /// <summary>
 511         /// 执行不返回数据集的SQL/存储过程
 512         /// </summary>
 513         /// <param name="type">SQL类型</param>
 514         /// <param name="sql">SQL</param>
 515         /// <param name="parameters">参数列表</param>
 516         /// <returns>影响行数</returns>
 517         public int ExecuteSql(CommandType type, string sql, params IDbDataParameter[] parameters)
 518         {
 519             try
 520             {
 521                 int result;
 522                 _cmd.CommandType = type;
 523                 _cmd.CommandText = sql;
 524                 _cmd.Connection = _conn;
 525                 ReSetParameters(_cmd, parameters);
 526                 if (_useTransaction)
 527                 {
 528                     result = _cmd.ExecuteNonQuery();
 529                 }
 530                 else
 531                 {
 532                     Open();
 533                     result = _cmd.ExecuteNonQuery();
 534                     Close();
 535                 }
 536                 return result;
 537             }
 538             catch
 539             {
 540                 DoCatch();
 541                 throw;
 542             }
 543         }
 544 
 545         /// <summary>
 546         /// 执行不返回数据集的SQL
 547         /// </summary>
 548         /// <param name="sql">SQL</param>
 549         /// <param name="parameters">参数列表</param>
 550         /// <returns>影响行数</returns>
 551         public int ExecuteSql(string sql, params IDbDataParameter[] parameters)
 552         {
 553             try
 554             {
 555                 int result;
 556                 _cmd.CommandType = CommandType.Text;
 557                 _cmd.CommandText = sql;
 558                 _cmd.Connection = _conn;
 559                 ReSetParameters(_cmd, parameters);
 560                 if (_useTransaction)
 561                 {
 562                     result = _cmd.ExecuteNonQuery();
 563                 }
 564                 else
 565                 {
 566                     Open();
 567                     result = _cmd.ExecuteNonQuery();
 568                     Close();
 569                 }
 570                 return result;
 571             }
 572             catch
 573             {
 574                 DoCatch();
 575                 throw;
 576             }
 577         }
 578 
 579         /// <summary>
 580         /// 执行不返回数据集的SQL/存储过程
 581         /// </summary>
 582         /// <param name="cmd">IDbCommand</param>
 583         /// <param name="parameters">参数列表</param>
 584         /// <returns>影响行数</returns>
 585         public int ExecuteSql(IDbCommand cmd, params IDbDataParameter[] parameters)
 586         {
 587             try
 588             {
 589                 int result;
 590                 cmd.Connection = _conn;
 591                 ReSetParameters(cmd, parameters);
 592                 if (_useTransaction)
 593                 {
 594                     result = cmd.ExecuteNonQuery();
 595                 }
 596                 else
 597                 {
 598                     Open();
 599                     result = cmd.ExecuteNonQuery();
 600                     Close();
 601                 }
 602                 return result;
 603             }
 604             catch
 605             {
 606                 DoCatch();
 607                 throw;
 608             }
 609         }
 610 
 611         /// <summary>
 612         /// 返回首行首列
 613         /// </summary>
 614         /// <param name="sql"></param>
 615         /// <returns></returns>
 616         public object GetSingle(string sql)
 617         {
 618             try
 619             {
 620                 object result;
 621                 _cmd.CommandType = CommandType.Text;
 622                 _cmd.CommandText = sql;
 623                 _cmd.Connection = _conn;
 624                 _cmd.Parameters.Clear();
 625 
 626                 if (_useTransaction)
 627                     result = _cmd.ExecuteScalar();
 628                 else
 629                 {
 630                     Open();
 631                     result = _cmd.ExecuteScalar();
 632                     Close();
 633                 }
 634                 return result;
 635             }
 636             catch
 637             {
 638                 DoCatch();
 639                 throw;
 640             }
 641         }
 642 
 643         /// <summary>
 644         /// 返回首行首列
 645         /// </summary>
 646         /// <param name="type">sql类型</param>
 647         /// <param name="sql">查询语句</param>
 648         /// <param name="parameters">参数列表</param>
 649         /// <returns></returns>
 650         public object GetSingle(CommandType type, string sql, params IDbDataParameter[] parameters)
 651         {
 652             try
 653             {
 654                 object result;
 655                 _cmd.CommandType = type;
 656                 _cmd.CommandText = sql;
 657                 _cmd.Connection = _conn;
 658                 ReSetParameters(_cmd, parameters);
 659 
 660                 if (_useTransaction)
 661                     result = _cmd.ExecuteScalar();
 662                 else
 663                 {
 664                     Open();
 665                     result = _cmd.ExecuteScalar();
 666                     Close();
 667                 }
 668                 return result;
 669             }
 670             catch
 671             {
 672                 DoCatch();
 673                 throw;
 674             }
 675         }
 676 
 677         /// <summary>
 678         /// 返回首行首列
 679         /// </summary>
 680         /// <param name="sql">查询语句</param>
 681         /// <param name="parameters">参数列表</param>
 682         /// <returns></returns>
 683         public object GetSingle(string sql, params IDbDataParameter[] parameters)
 684         {
 685             try
 686             {
 687                 object result;
 688                 _cmd.CommandType = CommandType.Text;
 689                 _cmd.CommandText = sql;
 690                 _cmd.Connection = _conn;
 691                 ReSetParameters(_cmd, parameters);
 692 
 693                 if (_useTransaction)
 694                     result = _cmd.ExecuteScalar();
 695                 else
 696                 {
 697                     Open();
 698                     result = _cmd.ExecuteScalar();
 699                     Close();
 700                 }
 701                 return result;
 702             }
 703             catch
 704             {
 705                 DoCatch();
 706                 throw;
 707             }
 708         }
 709 
 710         /// <summary>
 711         /// 返回首行首列
 712         /// </summary>
 713         /// <param name="cmd">IDbCommand</param>
 714         /// <param name="parameters">参数列表</param>
 715         /// <returns></returns>
 716         public object GetSingle(IDbCommand cmd, params IDbDataParameter[] parameters)
 717         {
 718             try
 719             {
 720                 object result;
 721                 cmd.Connection = _conn;
 722                 ReSetParameters(cmd, parameters);
 723 
 724                 if (_useTransaction)
 725                     result = cmd.ExecuteScalar();
 726                 else
 727                 {
 728                     Open();
 729                     result = cmd.ExecuteScalar();
 730                     Close();
 731                 }
 732                 return result;
 733             }
 734             catch
 735             {
 736                 DoCatch();
 737                 throw;
 738             }
 739         }
 740 
 741         /// <summary>
 742         /// 返回Reader
 743         /// </summary>
 744         /// <param name="sql"></param>
 745         /// <returns></returns>
 746         public IDataReader CreateReader(string sql)
 747         {
 748             try
 749             {
 750                 IDataReader reader;
 751                 _cmd.CommandType = CommandType.Text;
 752                 _cmd.CommandText = sql;
 753                 _cmd.Connection = _conn;
 754                 _cmd.Parameters.Clear();
 755 
 756                 if (_useTransaction)
 757                     reader = _cmd.ExecuteReader();
 758                 else
 759                 {
 760                     Open();
 761                     reader = _cmd.ExecuteReader();
 762                 }
 763                 return reader;
 764             }
 765             catch
 766             {
 767                 DoCatch();
 768                 throw;
 769             }
 770         }
 771 
 772         /// <summary>
 773         /// 返回Reader,注意:一定要结束时手动关闭Reader、Connection
 774         /// </summary>
 775         /// <param name="type">sql类型</param>
 776         /// <param name="sql">查询语句</param>
 777         /// <param name="parameters">参数列表</param>
 778         /// <returns></returns>
 779         public IDataReader CreateReader(CommandType type, string sql, params IDbDataParameter[] parameters)
 780         {
 781             try
 782             {
 783                 IDataReader reader;
 784                 _cmd.CommandType = type;
 785                 _cmd.CommandText = sql;
 786                 _cmd.Connection = _conn;
 787                 ReSetParameters(_cmd, parameters);
 788 
 789                 if (_useTransaction)
 790                     reader = _cmd.ExecuteReader();
 791                 else
 792                 {
 793                     Open();
 794                     reader = _cmd.ExecuteReader();
 795                 }
 796                 return reader;
 797             }
 798             catch
 799             {
 800                 DoCatch();
 801                 throw;
 802             }
 803         }
 804 
 805         /// <summary>
 806         /// 返回Reader,注意:一定要结束时手动关闭Reader、Connection
 807         /// </summary>
 808         /// <param name="sql">查询语句</param>
 809         /// <param name="parameters">参数列表</param>
 810         /// <returns></returns>
 811         public IDataReader CreateReader(string sql, params IDbDataParameter[] parameters)
 812         {
 813             try
 814             {
 815                 IDataReader reader;
 816                 _cmd.CommandType = CommandType.Text;
 817                 _cmd.CommandText = sql;
 818                 _cmd.Connection = _conn;
 819                 ReSetParameters(_cmd, parameters);
 820 
 821                 if (_useTransaction)
 822                     reader = _cmd.ExecuteReader();
 823                 else
 824                 {
 825                     Open();
 826                     reader = _cmd.ExecuteReader();
 827                 }
 828                 return reader;
 829             }
 830             catch
 831             {
 832                 DoCatch();
 833                 throw;
 834             }
 835         }
 836 
 837         private void ReSetParameters(IDbCommand cmd, params IDbDataParameter[] parameters)
 838         {
 839             cmd.Parameters.Clear();
 840             if (parameters != null && parameters.Length > 0)
 841             {
 842                 for (int i = 0; i < parameters.Length; i++)
 843                 {
 844                     cmd.Parameters.Add(parameters[i]);
 845                 }
 846             }
 847         }
 848 
 849         /// <summary>
 850         /// 关闭Connection
 851         /// </summary>
 852         public void CloseReader()
 853         {
 854             CommitTransaction();
 855         }
 856 
 857         /// <summary>
 858         /// 创建和Connection(Open状态)相关联的cmd(sql预编译过)
 859         /// </summary>
 860         /// <param name="sql"></param>
 861         /// <returns></returns>
 862         public IDbCommand CreateCommand(string sql)
 863         {
 864             try
 865             {
 866                 Open();
 867                 IDbCommand dbCommand = _conn.CreateCommand();
 868                 dbCommand.Transaction = _transaction;
 869                 dbCommand.CommandText = sql;
 870                 dbCommand.Prepare();
 871                 return dbCommand;
 872             }
 873             catch
 874             {
 875                 DoCatch();
 876                 throw;
 877             }
 878         }
 879 
 880         /// <summary>
 881         /// 开始事务
 882         /// </summary>
 883         /// <returns></returns>
 884         public bool BeginTransaction()
 885         {
 886             try
 887             {
 888                 Open();
 889                 _transaction = _conn.BeginTransaction();
 890                 _cmd.Transaction = _transaction;
 891                 _useTransaction = true;
 892                 return true;
 893             }
 894             catch
 895             {
 896                 DoCatch();
 897                 throw;
 898             }
 899         }
 900 
 901         /// <summary>
 902         /// 提交事务
 903         /// </summary>
 904         /// <returns></returns>
 905         public bool CommitTransaction()
 906         {
 907             try
 908             {
 909                 if (_transaction != null && _transaction.Connection != null)
 910                 {
 911                     _transaction.Commit();
 912                     _transaction.Dispose();
 913                     _transaction = null;
 914                 }
 915                 Close();
 916                 _cmd.Transaction = null;
 917                 _useTransaction = false;
 918                 return true;
 919             }
 920             catch
 921             {
 922                 DoCatch();
 923                 throw;
 924             }
 925         }
 926 
 927         /// <summary>
 928         /// 回滚事务
 929         /// </summary>
 930         /// <returns></returns>
 931         public bool RollBackTransaction()
 932         {
 933             try
 934             {
 935                 if (_transaction != null && _transaction.Connection != null)
 936                 {
 937                     _transaction.Rollback();
 938                     _transaction.Dispose();
 939                     _transaction = null;
 940                 }
 941                 Close();
 942                 _cmd.Transaction = null;
 943                 _useTransaction = false;
 944                 return true;
 945             }
 946             catch
 947             {
 948                 DoCatch();
 949                 throw;
 950             }
 951         }
 952 
 953         /// <summary>
 954         /// 打开数据库
 955         /// </summary>
 956         protected void Open()
 957         {
 958             if (_conn != null && _conn.State != ConnectionState.Open)
 959             {
 960                 _conn.Open();
 961             }
 962         }
 963 
 964         /// <summary>
 965         /// 关闭数据库
 966         /// </summary>
 967         protected void Close()
 968         {
 969             if (_conn != null && _conn.State != ConnectionState.Closed)
 970             {
 971                 _conn.Close();
 972             }
 973         }
 974 
 975         /// <summary>
 976         /// 释放资源
 977         /// </summary>
 978         public void Dispose()
 979         {
 980             if (_transaction != null && _transaction.Connection != null)
 981             {
 982                 _transaction.Rollback();
 983                 _transaction.Dispose();
 984                 _transaction = null;
 985             }
 986             if (_cmd !=null)
 987             {
 988                 _cmd.Dispose();
 989                 _cmd = null;
 990             }
 991             Close();
 992             if (_conn != null)
 993             {
 994                 _conn.Dispose();
 995                 _conn = null;
 996             }
 997         }
 998 
 999         /// <summary>
1000         /// 向数据库插入实体对象
1001         /// </summary>
1002         /// <param name="entity">实体对象</param>
1003         /// <param name="ignoreProperties">忽略映射的属性</param>
1004         /// <returns></returns>
1005         public int Insert(object entity, params string[] ignoreProperties)
1006         {
1007             return ExecuteSql(MakeInsertSql(entity, ignoreProperties), MakeInsertParameters(entity, ignoreProperties));
1008         }
1009 
1010         /// <summary>
1011         /// 更新实体
1012         /// </summary>
1013         /// <param name="entity"></param>
1014         /// <param name="keys"></param>
1015         /// <returns></returns>
1016         public int Update(object entity, params string[] keys)
1017         {
1018             return ExecuteSql(MakeUpdateSql(entity, keys), MakeUpdateParameters(entity));
1019         }
1020 
1021         /// <summary>
1022         /// 生产Insert语句--带参数
1023         /// </summary>
1024         /// <param name="obj">实体对象</param>
1025         /// <param name="ignoreProperties">忽略自曾的属性</param>
1026         /// <returns></returns>
1027         private string MakeInsertSql(object obj, params string[] ignoreProperties)
1028         {
1029             var insertHeader = string.Format("Insert Into {0} (", obj.GetType().Name);
1030             var insertBody = ") Values(";
1031             var pro = new List<string>();
1032             pro.AddRange(ignoreProperties);
1033             foreach (PropertyInfo info in obj.GetType().GetProperties())
1034             {
1035                 if (pro.Count > 0 && pro.Contains(info.Name))
1036                     continue;
1037                 insertHeader += info.Name + ",";
1038                 insertBody += _parameterChar + info.Name + ",";
1039             }
1040             insertHeader = insertHeader.Substring(0, insertHeader.Length - 1);
1041             insertBody = insertBody.Substring(0, insertBody.Length - 1) + ")";
1042             return insertHeader + insertBody;
1043         }
1044 
1045         /// <summary>
1046         /// 为update产生sql脚本
1047         /// </summary>
1048         /// <param name="obj"></param>
1049         /// <param name="keys"></param>
1050         /// <returns></returns>
1051         private string MakeUpdateSql(object obj, params string[] keys)
1052         {
1053             var updateHeader = string.Format("Update {0} set", obj.GetType().Name);
1054             var updateWhere = " where 1=1";
1055             var pro = new List<string>();
1056             pro.AddRange(keys);
1057             foreach (PropertyInfo info in obj.GetType().GetProperties())
1058             {
1059                 if (pro.Count > 0 && pro.Contains(info.Name))
1060                 {
1061                     updateWhere += " and " + info.Name + "=" + _parameterChar + info.Name;
1062                     continue;
1063                 }
1064                 if (updateHeader.EndsWith("set"))
1065                     updateHeader += " " + info.Name + "=" + _parameterChar + info.Name;
1066                 else
1067                     updateHeader += ", " + info.Name + "=" + _parameterChar + info.Name;
1068             }
1069             return updateHeader + updateWhere;
1070         }
1071 
1072         /// <summary>
1073         /// 生产Insert参数
1074         /// </summary>
1075         /// <param name="obj">实体对象</param>
1076         /// <param name="ignoreProperties">忽略自曾的属性</param>
1077         /// <returns></returns>
1078         private IDbDataParameter[] MakeInsertParameters(object obj, params string[] ignoreProperties)
1079         {
1080             var parameters = new List<IDbDataParameter>();
1081             var pro = new List<string>();
1082             pro.AddRange(ignoreProperties);
1083             foreach (PropertyInfo info in obj.GetType().GetProperties())
1084             {
1085                 if (pro.Count > 0 && pro.Contains(info.Name))
1086                     continue;
1087                 object temp = info.GetValue(obj, null);
1088                 parameters.Add(GetParameter(_parameterChar + info.Name, temp ?? DBNull.Value));
1089             }
1090             return parameters.ToArray();
1091         }
1092 
1093         /// <summary>
1094         /// 为update产生sql参数
1095         /// </summary>
1096         /// <param name="obj"></param>
1097         /// <returns></returns>
1098         private IDbDataParameter[] MakeUpdateParameters(object obj)
1099         {
1100             var parameters = new List<IDbDataParameter>();
1101             foreach (PropertyInfo info in obj.GetType().GetProperties())
1102             {
1103                 object temp = info.GetValue(obj, null);
1104                 parameters.Add(GetParameter(_parameterChar + info.Name, temp ?? DBNull.Value));
1105             }
1106             return parameters.ToArray();
1107         }
1108         
1109     }
1110 
1111 
1112     /// <summary>
1113     /// DataTable和Entity的转换工具
1114     /// </summary>
1115     public static class DataTableUtility
1116     {
1117         /// <summary>
1118         /// DataTable To IList
1119         /// </summary>
1120         /// <typeparam name="T"></typeparam>
1121         /// <param name="dt"></param>
1122         /// <returns></returns>
1123         public static List<T> ToList<T>(this DataTable dt)
1124         {
1125             if (dt == null || dt.Rows.Count == 0) return null;
1126             var list = new List<T>();
1127             foreach (DataRow row in dt.Rows)
1128             {
1129                 T obj = row.ToEntity<T>();
1130                 list.Add(obj);
1131             }
1132             return list;
1133         }
1134 
1135         /// <summary>
1136         /// DataRow To T
1137         /// </summary>
1138         public static T ToEntity<T>(this DataRow row)
1139         {
1140             Type objType = typeof (T);
1141             T obj = Activator.CreateInstance<T>();
1142 
1143             foreach (DataColumn column in row.Table.Columns)
1144             {
1145                 PropertyInfo property = objType.GetProperty(column.ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
1146                 if (property == null || !property.CanWrite)
1147                 {
1148                     continue;
1149                 }
1150                 object value = row[column.ColumnName];
1151                 if (value == DBNull.Value) value = null;
1152 
1153                 property.SetValue(obj, value, null);
1154 
1155             }
1156             return obj;
1157         }
1158 
1159         /// <summary>
1160         /// List To DataTable
1161         /// </summary>
1162         /// <typeparam name="T"></typeparam>
1163         /// <param name="list"></param>
1164         /// <returns></returns>
1165         public static DataTable ToDataTable<T>(this List<T> list)
1166         {
1167             try
1168             {
1169                 Type objType = typeof (T);
1170                 DataTable dataTable = new DataTable(objType.Name);
1171                 if (list != null ? list.Count > 0 : false)
1172                 {
1173                     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
1174                     foreach (PropertyDescriptor property in properties)
1175                     {
1176                         Type propertyType = property.PropertyType;
1177 
1178                         //nullables must use underlying types
1179                         if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
1180                             propertyType = Nullable.GetUnderlyingType(propertyType);
1181                         //enums also need special treatment
1182                         if (propertyType.IsEnum)
1183                             propertyType = Enum.GetUnderlyingType(propertyType); //probably Int32
1184 
1185                         dataTable.Columns.Add(property.Name, propertyType);
1186                     }
1187 
1188                     foreach (T li in list)
1189                     {
1190                         DataRow row = dataTable.NewRow();
1191                         foreach (PropertyDescriptor property1 in properties)
1192                         {
1193                             row[property1.Name] = property1.GetValue(li) ?? DBNull.Value; //can‘t use null
1194                         }
1195                         dataTable.Rows.Add(row);
1196 
1197                     }
1198                 }
1199                 return dataTable;
1200             }
1201             catch
1202             {
1203                 return null;
1204             }
1205         }
1206     }
1207 
1208 }

 

来,纪念一下。

Db - DataAccess

标签:rollback   into   rtp   nstat   scalar   case   连接字符串   开始   reader   

原文地址:http://www.cnblogs.com/jonney-wang/p/7101224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!