C#通用数据库操作类 支持Access/MSSql/Orale/MySql等数据库

时间:2022-09-20 18:27:27
[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Common;  
  5.   
  6. namespace DbHelper  
  7. {  
  8.     /// <summary>  
  9.     /// 通用数据库访问类,封装了对数据库的常见操作  
  10.     ///</summary>  
  11.     public sealed class DbUtility  
  12.     {  
  13.         public string ConnectionString { getset; }  
  14.         private DbProviderFactory providerFactory;  
  15.         /// <summary>  
  16.         /// 构造函数  
  17.         /// </summary>  
  18.         /// <param name="connectionString">数据库连接字符串</param>  
  19.         /// <param name="providerType">数据库类型枚举,参见<paramref name="providerType"/></param>  
  20.         public DbUtility(string connectionString, DbProviderType providerType)  
  21.         {  
  22.             ConnectionString = connectionString;  
  23.             providerFactory = ProviderFactory.GetDbProviderFactory(providerType);  
  24.             if (providerFactory == null)  
  25.             {  
  26.                 throw new ArgumentException("Can't load DbProviderFactory for given value of providerType");  
  27.             }  
  28.         }  
  29.         /// <summary>     
  30.         /// 对数据库执行增删改操作,返回受影响的行数。     
  31.         /// </summary>     
  32.         /// <param name="sql">要执行的增删改的SQL语句</param>     
  33.         /// <param name="parameters">执行增删改语句所需要的参数</param>  
  34.         /// <returns></returns>    
  35.         public int ExecuteNonQuery(string sql, IList<DbParameter> parameters)  
  36.         {  
  37.             return ExecuteNonQuery(sql, parameters, CommandType.Text);  
  38.         }  
  39.         /// <summary>     
  40.         /// 对数据库执行增删改操作,返回受影响的行数。     
  41.         /// </summary>     
  42.         /// <param name="sql">要执行的增删改的SQL语句</param>     
  43.         /// <param name="parameters">执行增删改语句所需要的参数</param>  
  44.         /// <param name="commandType">执行的SQL语句的类型</param>  
  45.         /// <returns></returns>  
  46.         public int ExecuteNonQuery(string sql, IList<DbParameter> parameters, CommandType commandType)  
  47.         {  
  48.             using (DbCommand command = CreateDbCommand(sql, parameters, commandType))  
  49.             {  
  50.                 command.Connection.Open();  
  51.                 int affectedRows = command.ExecuteNonQuery();  
  52.                 command.Connection.Close();  
  53.                 return affectedRows;  
  54.             }  
  55.         }  
  56.   
  57.         /// <summary>     
  58.         /// 执行一个查询语句,返回一个关联的DataReader实例     
  59.         /// </summary>     
  60.         /// <param name="sql">要执行的查询语句</param>     
  61.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>  
  62.         /// <returns></returns>   
  63.         public DbDataReader ExecuteReader(string sql, IList<DbParameter> parameters)  
  64.         {  
  65.             return ExecuteReader(sql, parameters, CommandType.Text);  
  66.         }  
  67.   
  68.         /// <summary>     
  69.         /// 执行一个查询语句,返回一个关联的DataReader实例     
  70.         /// </summary>     
  71.         /// <param name="sql">要执行的查询语句</param>     
  72.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>  
  73.         /// <param name="commandType">执行的SQL语句的类型</param>  
  74.         /// <returns></returns>   
  75.         public DbDataReader ExecuteReader(string sql, IList<DbParameter> parameters, CommandType commandType)  
  76.         {  
  77.             DbCommand command = CreateDbCommand(sql, parameters, commandType);  
  78.             command.Connection.Open();  
  79.             return command.ExecuteReader(CommandBehavior.CloseConnection);  
  80.         }  
  81.   
  82.         /// <summary>     
  83.         /// 执行一个查询语句,返回一个包含查询结果的DataTable     
  84.         /// </summary>     
  85.         /// <param name="sql">要执行的查询语句</param>     
  86.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>  
  87.         /// <returns></returns>  
  88.         public DataTable ExecuteDataTable(string sql, IList<DbParameter> parameters)  
  89.         {  
  90.             return ExecuteDataTable(sql, parameters, CommandType.Text);  
  91.         }  
  92.         /// <summary>     
  93.         /// 执行一个查询语句,返回一个包含查询结果的DataTable     
  94.         /// </summary>     
  95.         /// <param name="sql">要执行的查询语句</param>     
  96.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>  
  97.         /// <param name="commandType">执行的SQL语句的类型</param>  
  98.         /// <returns></returns>  
  99.         public DataTable ExecuteDataTable(string sql, IList<DbParameter> parameters, CommandType commandType)  
  100.         {  
  101.             using (DbCommand command = CreateDbCommand(sql, parameters, commandType))  
  102.             {  
  103.                 using (DbDataAdapter adapter = providerFactory.CreateDataAdapter())  
  104.                 {  
  105.                     adapter.SelectCommand = command;  
  106.                     DataTable data = new DataTable();  
  107.                     adapter.Fill(data);  
  108.                     return data;  
  109.                 }  
  110.             }  
  111.         }  
  112.   
  113.         /// <summary>     
  114.         /// 执行一个查询语句,返回查询结果的第一行第一列     
  115.         /// </summary>     
  116.         /// <param name="sql">要执行的查询语句</param>     
  117.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>     
  118.         /// <returns></returns>     
  119.         public Object ExecuteScalar(string sql, IList<DbParameter> parameters)  
  120.         {  
  121.             return ExecuteScalar(sql, parameters, CommandType.Text);  
  122.         }  
  123.   
  124.         /// <summary>     
  125.         /// 执行一个查询语句,返回查询结果的第一行第一列     
  126.         /// </summary>     
  127.         /// <param name="sql">要执行的查询语句</param>     
  128.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>     
  129.         /// <param name="commandType">执行的SQL语句的类型</param>  
  130.         /// <returns></returns>     
  131.         public Object ExecuteScalar(string sql, IList<DbParameter> parameters, CommandType commandType)  
  132.         {  
  133.             using (DbCommand command = CreateDbCommand(sql, parameters, commandType))  
  134.             {  
  135.                 command.Connection.Open();  
  136.                 object result = command.ExecuteScalar();  
  137.                 command.Connection.Close();  
  138.                 return result;  
  139.             }  
  140.         }  
  141.   
  142.         public DbParameter CreateDbParameter(string name, object value)  
  143.         {  
  144.             return CreateDbParameter(name, ParameterDirection.Input, value);  
  145.         }  
  146.   
  147.         public DbParameter CreateDbParameter(string name, ParameterDirection parameterDirection, object value)  
  148.         {  
  149.             DbParameter parameter = providerFactory.CreateParameter();  
  150.             parameter.ParameterName = name;  
  151.             parameter.Value = value;  
  152.             parameter.Direction = parameterDirection;  
  153.             return parameter;  
  154.         }  
  155.   
  156.         /// <summary>  
  157.         /// 创建一个DbCommand对象  
  158.         /// </summary>  
  159.         /// <param name="sql">要执行的查询语句</param>     
  160.         /// <param name="parameters">执行SQL查询语句所需要的参数</param>  
  161.         /// <param name="commandType">执行的SQL语句的类型</param>  
  162.         /// <returns></returns>  
  163.         private DbCommand CreateDbCommand(string sql, IList<DbParameter> parameters, CommandType commandType)  
  164.         {  
  165.             DbConnection connection = providerFactory.CreateConnection();  
  166.             DbCommand command = providerFactory.CreateCommand();  
  167.             connection.ConnectionString = ConnectionString;  
  168.             command.CommandText = sql;  
  169.             command.CommandType = commandType;  
  170.             command.Connection = connection;  
  171.             if (!(parameters == null || parameters.Count == 0))  
  172.             {  
  173.                 foreach (DbParameter parameter in parameters)  
  174.                 {  
  175.                     command.Parameters.Add(parameter);  
  176.                 }  
  177.             }  
  178.             return command;  
  179.         }  
  180.     }  
  181.     /// <summary>  
  182.     /// 数据库类型枚举  
  183.     /// </summary>  
  184.     public enum DbProviderType : byte  
  185.     {  
  186.         SqlServer,  
  187.         MySql,  
  188.         SQLite,  
  189.         Oracle,  
  190.         ODBC,  
  191.         OleDb,  
  192.         Firebird,  
  193.         PostgreSql,  
  194.         DB2,  
  195.         Informix,  
  196.         SqlServerCe  
  197.     }  
  198.     /// <summary>  
  199.     /// DbProviderFactory工厂类  
  200.     /// </summary>  
  201.     public class ProviderFactory  
  202.     {  
  203.         private static Dictionary<DbProviderType, string> providerInvariantNames = new Dictionary<DbProviderType, string>();  
  204.         private static Dictionary<DbProviderType, DbProviderFactory> providerFactoies = new Dictionary<DbProviderType, DbProviderFactory>(20);  
  205.         static ProviderFactory()  
  206.         {  
  207.             //加载已知的数据库访问类的程序集  
  208.             providerInvariantNames.Add(DbProviderType.SqlServer, "System.Data.SqlClient");  
  209.             providerInvariantNames.Add(DbProviderType.OleDb, "System.Data.OleDb");  
  210.             providerInvariantNames.Add(DbProviderType.ODBC, "System.Data.ODBC");  
  211.             providerInvariantNames.Add(DbProviderType.Oracle, "Oracle.DataAccess.Client");  
  212.             providerInvariantNames.Add(DbProviderType.MySql, "MySql.Data.MySqlClient");  
  213.             providerInvariantNames.Add(DbProviderType.SQLite, "System.Data.SQLite");  
  214.             providerInvariantNames.Add(DbProviderType.Firebird, "FirebirdSql.Data.Firebird");  
  215.             providerInvariantNames.Add(DbProviderType.PostgreSql, "Npgsql");  
  216.             providerInvariantNames.Add(DbProviderType.DB2, "IBM.Data.DB2.iSeries");  
  217.             providerInvariantNames.Add(DbProviderType.Informix, "IBM.Data.Informix");  
  218.             providerInvariantNames.Add(DbProviderType.SqlServerCe, "System.Data.SqlServerCe");  
  219.         }  
  220.         /// <summary>  
  221.         /// 获取指定数据库类型对应的程序集名称  
  222.         /// </summary>  
  223.         /// <param name="providerType">数据库类型枚举</param>  
  224.         /// <returns></returns>  
  225.         public static string GetProviderInvariantName(DbProviderType providerType)  
  226.         {  
  227.             return providerInvariantNames[providerType];  
  228.         }  
  229.         /// <summary>  
  230.         /// 获取指定类型的数据库对应的DbProviderFactory  
  231.         /// </summary>  
  232.         /// <param name="providerType">数据库类型枚举</param>  
  233.         /// <returns></returns>  
  234.         public static DbProviderFactory GetDbProviderFactory(DbProviderType providerType)  
  235.         {  
  236.             //如果还没有加载,则加载该DbProviderFactory  
  237.             if (!providerFactoies.ContainsKey(providerType))  
  238.             {  
  239.                 providerFactoies.Add(providerType, ImportDbProviderFactory(providerType));  
  240.             }  
  241.             return providerFactoies[providerType];  
  242.         }  
  243.         /// <summary>  
  244.         /// 加载指定数据库类型的DbProviderFactory  
  245.         /// </summary>  
  246.         /// <param name="providerType">数据库类型枚举</param>  
  247.         /// <returns></returns>  
  248.         private static DbProviderFactory ImportDbProviderFactory(DbProviderType providerType)  
  249.         {  
  250.             string providerName = providerInvariantNames[providerType];  
  251.             DbProviderFactory factory = null;  
  252.             try  
  253.             {  
  254.                 //从全局程序集中查找  
  255.                 factory = DbProviderFactories.GetFactory(providerName);  
  256.             }  
  257.             catch (ArgumentException e)  
  258.             {  
  259.                 factory = null;  
  260.             }  
  261.             return factory;  
  262.         }  
  263.     }  
  264. }  
[csharp] view plaincopyprint?
  1. //使用示例 SQLite  
  2. string connectionString = @"Data Source=D:\VS2008\NetworkTime\CrawlApplication\CrawlApplication.db3";  
  3. string sql = "SELECT * FROM Weibo_Media order by Id desc limit 0,20000";  
  4. DbUtility db = new DbUtility(connectionString, DbProviderType.SQLite);  
  5. DataTable data = db.ExecuteDataTable(sql, null);  
  6. DbDataReader reader = db.ExecuteReader(sql, null);  
  7. reader.Close();   
  8. //使用示例 MySql  
  9. string connectionString = @"Server=localhost;Database=crawldb;Uid=root;Pwd=root;Port=3306;";  
  10. string sql = "SELECT * FROM Weibo_Media order by Id desc limit 0,20000";  
  11. DbUtility db = new DbUtility(connectionString, DbProviderType.MySql);  
  12. DataTable data = db.ExecuteDataTable(sql, null);  
  13. DbDataReader reader = db.ExecuteReader(sql, null);  
  14. reader.Close();   
  15. //使用示例 Execl  
  16. string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/XLS/车型.xls") + ";Extended Properties=Excel 8.0;";  
  17. string sql = "SELECT * FROM [Sheet1$]";  
  18. DbUtility db = new DbUtility(connectionString, DbProviderType.OleDb);  
  19. DataTable data = db.ExecuteDataTable(sql, null);