我们正在做一个相当严肃的应用程序,需要对客户端想要使用的数据库保持不可知.最初我们计划支持
MySQL,Oracle& sql Server.表&视图是简单的查询(没有真正的奇特的sql),因此问题:
>使用本机DB驱动程序(MysqLDbConnection等),并封装执行查询和处理结果的逻辑
>使用通用OleDbConnection
显然,选项2不涉及开销,但我认为性能不如本地访问那么好?
解决方法
Note: This answer is relevant if you decide to use basic ADO.NET 2 functionality instead of an ORM (such as Entity Framework or NHibernate) or LINQ to sql.
假设你有一个在你的app.config中定义的连接字符串:
- <connectionStrings>
- <add name="SomeConnection"
- providerName="System.Data.sqlClient"
- connectionString="..." />
- </connectionStrings>
请注意providerName属性及其值的存在.您也可以为另一个DB提供商(例如,System.Data.sqlite.
(请注意,非标准提供程序,即默认情况下不在.NET Framework中的那些,首先应用在app.config或客户机的machine.config中).
现在,您可以按照完全提供者无关的方式使用指定的数据库,如下所示:
- using System.Configuration; // for ConfigurationManager
- using System.Data; // for all interface types
- using System.Data.Common; // for DbProviderFactories
- var cs = ConfigurationManager.ConnectionStrings["SomeConnection"];
- // ^^^^^^^^^^^^^^^^
- var factory = DbProviderFactories.GetFactory(cs.ProviderName);
- // ^^^^^^^^^^^^^^^
- using (IDbConnection connection = factory.CreateConnection())
- {
- connection.ConnectionString = cs.ConnectionString;
- // ^^^^^^^^^^^^^^^^^^^
- connection.Open();
- try
- {
- using (IDbCommand command = connection.CreateCommand())
- {
- ... // do something with the database
- }
- }
- finally
- {
- connection.Close();
- }
- }
请注意,此代码仅适用于接口类型.指定特定DB提供程序的唯一地方是通过app.config文件中的providerName属性值. (我已经标记了所有使用app.config设置的地方用^^^.)
进一步阅读:
> Generic Coding with the ADO.NET 2.0 Base Classes and Factories:
类似于我的答案,但更详细.
> ADO.NET Managed Providers and DataSet Developer Center:其中包括可用的ADO.NET数据库提供程序的索引.