如何从用户指定的连接字符串检测提供程序? [英] How do i detect the provider from a user-specified connectionstring?

查看:134
本文介绍了如何从用户指定的连接字符串检测提供程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要针对用户指定的连接字符串执行特定的查询。查询将需要一些参数,所以我正在考虑使用DbProviderFactory,结合 myConnection.GetSchema(DataSourceInformation)。Rows [0] [ParameterMarkerFormat] 以查明是否需要使用(Oracle), @ (Sql)或

My application needs to do a certain query against a user-specified connectionstring. The query will need some parameters, so I was thinking of using the DbProviderFactory , in combination with myConnection.GetSchema("DataSourceInformation").Rows[0]["ParameterMarkerFormat"] to find out if I need to use :(Oracle), @(Sql) or ?(OleDb) to send in the parameters to the database.

要使用DbProviderFactory,我需要找出需要什么Provider的一个连接串。是否有一个好的方法来做到这一点,或者我需要使用某种 if(conStr.indexOf(oledb)!= -1){type = DbTypes.OleDB; } logic? (或者有更好的方法连接到一个未知的数据库类型吗?)

To use the DbProviderFactory I need to find out what Provider is needed for a connectionstring. Is there a good way to do this, or do I need to use some sort of if(conStr.indexOf("oledb") != -1) { type = DbTypes.OleDB; } logic? (Or is there a better way to connect to an "unknown" database type?)

注意:DbProviderFactory期望提供程序的形式是 System.Data.SqlClient ,而不是实际的connectionstring中的 SQLNCLI.1

Note: The DbProviderFactory expects the provider to be in the form of System.Data.SqlClient, not the SQLNCLI.1 that is in the actual connectionstring.

推荐答案

事情是连接字符串只有在提供者的上下文中有意义,而不是相反。换句话说,没有基于字符串标识提供程序的标准。也就是说,你通常可以使用IndexOf从字符串中推断出提供者。

The thing is that a connection string has meaning only in the context of the provider and not the other way around. In other words there's no standard for identifying the provider based on the string. That said, you can generally infer the provider from the string as you've demonstrated with using IndexOf.

您可以使用静态方法DbProviderFactories获取已安装提供者的列表。 GetFactoryClasses()。这将为每个提供程序返回一行DataTable。该行将具有列InvariantName,它将提供正确的值传递给DbProviderFactories.GetFactory。如果您的应用程序设计允许,您可以在获取连接字符串的同时公开可用提供程序的列表,以便您的用户可以指定他们打算建立连接的提供程序。 名称列用于该目的。

You can get a list of installed providers using the static method DbProviderFactories.GetFactoryClasses(). This will return a DataTable with a row for each provider. The row will have the column "InvariantName" that will give you the correct value to pass to DbProviderFactories.GetFactory. If your application design allows, you can expose the list of available providers at the same time you get the connection string so your users can specify which provider they intend to make the connection. The "Name" column is intended for that very purpose.

这篇关于如何从用户指定的连接字符串检测提供程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆