Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Database Name from Connection String using SqlConnectionStringBuilder

I do not want to split connection strings using string manipulation functions to get Server, Database, Username, and Password.

I read the following link and read the accepted answer, I found that is the best way to get username and password out from connection string, but what about Database Name?

Right way to get username and password from connection string?

How to get Database Name from Connection String using SqlConnectionStringBuilder. (does the DataSource is the Server name?)

like image 523
Imran Rizvi Avatar asked May 11 '12 11:05

Imran Rizvi


People also ask

What is database name in connection string?

Database name is a value of SqlConnectionStringBuilder. InitialCatalog property.

How do I find my database connection string?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.

How do I find the database connection string in Visual Studio?

Open Visual Studio.Go to view => Server Explorer. Right click on Data Connections and select Add Connection (or) click on Connect to Database icon. You will get add connection window. Provide Server name.


1 Answers

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; 
like image 94
Romil Kumar Jain Avatar answered Oct 09 '22 00:10

Romil Kumar Jain