如果我们用access数据库,连接是这样定义的OleDbConnection,如果连接SQL Server就得用SqlDbConnection,请问有什么办法可以使更换数据库的时候,只要改动极少的代码,而不需要把所有的OleDbConnection都改成SqlDbConnection?

解决方案 »

  1.   

    连接SQL   Server不是必须用SqlDbConnection,OLEDbConnection也可以啊
    如果要适用多数据库,最好写一个类,专门负责处理与不同数据库的交互
      

  2.   

    写一个类using System.Data.Common;  

    DbConnection
    DbCommand
      

  3.   

    首先,使用一个支持多种数据库的框架本身非常麻烦。我见过的框架除了现成的OleDB一套,就是CodeGear手里的Borland Data Provider for .NET和DBExpress for .NET——这两个只能在Delphi for .NET里面用。其次,请在设计时就确定使用什么数据库。一般来说实际的项目需要迁移数据库的可能性几乎是0,所以从来没见过需要在编码时支持多种数据库的。毕竟C#代码支持好了,可是不同的数据库SQL语法又不一样,到头来要改的东西实在是太多了,甚至不如把整个DAL重做来的简单。
      

  4.   

    写一个类 using   System.Data.Common;     
    用 
    DbConnection 
    DbCommand
    --------------------------------------
    能不能给出具体的代码?
      

  5.   

    using System.Configuration;
    using System.Data.Common;
    using System.Data.SqlClient;
    ...
    DbConnection conn = null;
    ConnectionStringSettings s = ConfigurationSettings.ConnectionStrings["ConnectionStrings"];DbProviderFactory factory = DbProviderFactories.GetFactory(s.ProviderName);if ((factory.SupportedClasses & DbProviderSupportedClasses.DbConnection) > 0)
    {
    conn = factory.CreateConnection();
    conn.ConnectionString = s.ConnectionString;
    }DbCommand selectCommand = null;
    if ((factory.SupportedClasses & DbProviderSupportedClasses.DbCommand) > 0)
    {
    selectCommand = factory.CreateCommand();
    selectCommand.CommandText = "SELECT * from dbo.Customers";
    selectCommand.Connection = conn;
    }conn.Open();DbDataReader dataReader = selectCommand.ExecuteReader();while (dataReader.Read())
    Console.WriteLine(sqlDataReader.GetString(0));conn.Close();