如何使用 SqlConnectionStringBuilder 从连接字符串获取数据库名称

我不想使用字符串操作函数拆分连接字符串以获取 Server、 Database、 Username 和 Password。

我读了下面的链接,并阅读了接受的答案,我发现这是最好的方式获得用户名和密码从连接字符串,但什么是数据库名称?

从连接字符串获取用户名和密码的正确方法?

如何使用 SqlConnectionStringBuilder 从连接字符串获取数据库名称(DataSource 是服务器名称吗?)

138443 次浏览

See MSDN documentation for InitialCatalog Property:

Gets or sets the name of the database associated with the connection...

This property corresponds to the "Initial Catalog" and "database" keys within the connection string...

Database name is a value of SqlConnectionStringBuilder.InitialCatalog property.

You can use InitialCatalog Property or builder["Database"] works as well. I tested it with different case and it still works.

string connectString = "Data Source=(local);" + "Integrated Security=true";


SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);


Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);

You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);


string server = builder.DataSource;
string database = builder.InitialCatalog;

or

System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();


builder.ConnectionString = connectionString;


string server = builder["Data Source"] as string;
string database = builder["Initial Catalog"] as string;

this gives you the Xact;

System.Data.SqlClient.SqlConnectionStringBuilder connBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();


connBuilder.ConnectionString = connectionString;


string server = connBuilder.DataSource;           //-> this gives you the Server name.
string database = connBuilder.InitialCatalog;     //-> this gives you the Db name.

A much simpler alternative is to get the information from the connection object itself. For example:

IDbConnection connection = new SqlConnection(connectionString);
var dbName = connection.Database;

Similarly you can get the server name as well from the connection object.

DbConnection connection = new SqlConnection(connectionString);
var server = connection.DataSource;