微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#ADO.NET中数据库驱动程序访问的通用方法

我必须编写一个小型C#程序,它将以动态方式处理至少三个不同的数据库供应商(Oracle,Sybase ASE,sqlServer). (它将依靠客户选择来选择数据库)

我决定通过ado.net数据提供商使用“纯”托管驱动程序.

但是,当我尝试连接时,我希望代码是“一行来统治它们”,就像JDBC一样:

DriverManager.getConnection(connection_string);

而不是这个,感到惊讶,我必须为每个驱动程序编写其特定的代码

sqlConnection() for sqlServer 

AseConnection() for Sybase

OracleConnection(),etc.

当然,我应该用自己封装 – 所有这些都在抽象方法和动态加载中,但我想知道为什么在.net中不存在这样的东西

嗯,我感觉我错过了什么

解决方法

由于您在计算机上安装了相应数据库的.Net Provider,因此可以使用 DbProviderFactory作为示例:

包括

using System.Data.Common;

并尝试这样的事情:

// create the provider factory from the namespace provider
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.sqlClient"); 

// you Could create any other provider factory.. for Oracle,MysqL,etc...


// use the factory object to create Data access objects.
DbConnection connection = factory.CreateConnection(); // will return the connection object,in this case,sqlConnection ...

connection.ConnectionString = "read connection string from somewhere.. .config file for sample";


try
{
   // open connection
   connection.open();

   // create command to execute queries...
   DbCommand command = connection.CreateCommand(); // create a sqlCommand,OracleCommand etc... depende of the provider factory configured.

   // some logic 
}
catch 
{
}
finally 
{
   // close connection
   connection.Close();
}

要知道,您的应用程序可以找到哪些提供程序,您可以使用DbProviderFactories.GetFactoryClasses()方法获取DataTable,其中包含计算机上安装的每个提供程序的详细信息.

原文地址:https://www.jb51.cc/c/118972.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐