C# 通过连接字符串检索正确的 DbConnection 对象
我有一个连接字符串传递给一个函数,我需要根据该字符串创建一个基于 DbConnection 的对象(即 SQLConnection、OracleConnection、OLEDbConnection 等)。
是否有任何内置功能可以执行此操作,或者有任何第三方库可以提供帮助。 我们不一定要构建此连接字符串,因此我们不能依赖字符串写入的格式来确定其类型,并且我希望不必对可能连接的所有组合和排列进行编码字符串
I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string.
Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would prefer not to have to code up all combinations and permutations of possible connection strings
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 2.0 或更高版本的框架,并且可以让它们通过驱动程序类传入第二个字符串,则可以使用 dbProviderFactory 类为您加载驱动程序。
以下是 Factory 类的 MSDN 链接:
http://msdn.microsoft.com/en-us/library/wda6c36e.aspx
if you're using framework 2.0 or above, and you can get them to pass in a second string with the driver class, you can use the dbProviderFactory class to load the driver for you.
Here's an MSDN link to the Factory class:
http://msdn.microsoft.com/en-us/library/wda6c36e.aspx
您应该能够解析 Provider 部分并将其传递到 DbProviderFactories.GetFactory 中,它将返回 OdbcFactory、OleDbFactory 或 SqlClientFactory,然后让您执行 CreateConnection 等。
我不确定这将如何与 Oracle 一起使用,除非他们提供 OracleDbFactory 。
You should be able to parse out the Provider section and pass it into DbProviderFactories.GetFactory which will return a OdbcFactory, OleDbFactory or SqlClientFactory and let you then perform CreateConnection etc.
I'm not sure how this would work with Oracle unless they provide an OracleDbFactory.
大多数连接字符串(至少在 .NET 2.0 中)也有一个与之配套的providerName 属性。 因此,SQL 连接字符串将具有一个提供程序名称,例如:
因此,您的方法需要接受连接字符串和提供程序名称,然后您可以使用 DbProviderFactory 正如 damieng 提到的。
Most connection strings (at least in .NET 2.0) also have a providerName property that goes with them. So a SQL connection string will have a provider Name like:
So your method would need to accept both the connection string and the provider name and then you could use the DbProviderFactory as mentioned by damieng.