Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database Connection String Info

Tags:

c#

In .Net is there a class in .Net where you can get the DB name, and all the connection string info without acutally doing a substring on the connection string?

EDIT:

I am not creating a connection I am attempting to get info out of the connection string. So I am basicly looking for something that takes a connection string arg and has accessors to dbName, connection type, etc....

like image 514
Ted Smith Avatar asked Apr 01 '09 17:04

Ted Smith


People also ask

What is 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.

What does a connection string contain?

A connection string contains initialization information that is passed as a parameter from a data provider to a data source.


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:

Given

string connectionString = "Data Source = .\\SQLEXPRESS;Database=Northwind;Integrated Security=True;";

You could do...

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

builder.ConnectionString = connectionString;

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

Or

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

builder.ConnectionString = connectionString;

string server = builder.DataSource;
string database = builder.InitialCatalog;
like image 131
Adam Robinson Avatar answered Oct 04 '22 11:10

Adam Robinson