Explain Codes LogoExplain Codes Logo

How to get Database Name from Connection String using SqlConnectionStringBuilder

sql
connection-string-syntax
sqlconnectionstringbuilder
database-connection
Nikita BarsukovbyNikita Barsukov·Sep 8, 2024
TLDR
var builder = new SqlConnectionStringBuilder("Server=myServer;Database=myDB;..."); string dbName = builder.InitialCatalog;

Get the database name from the InitialCatalog property of the SqlConnectionStringBuilder class.

SqlConnectionStringBuilder: A programmer's new best friend

The SqlConnectionStringBuilder class is a capable tool within the System.Data.SqlClient namespace. It eliminates the need for manual and error-prone parsing of connection strings.

A direct line to vital info

Want the database name? Use builder.InitialCatalog. Need the server name? builder.DataSource is your key. This direct line to your vital info bypasses cumbersome string manipulation.

Versatility is the name of the game

Different database providers, different keywords. SqlConnectionStringBuilder knows how to play ball. It handles provider-specific connection strings with ease, making it your trusted utility across the board.

Setting up secure connections

If you wish to secure your connections further, consider utilizing Integrated Security=true. Assigning to connBuilder.ConnectionString neatly separates the parameters for an optimally secure connection setup.

Expanding skills through IDbConnection

The IDbConnection interface is another way you can interact with databases. Just like SqlConnectionStringBuilder, IDbConnection removes the need to manually parse strings. Here's a handy example:

// Let's make a connection, shall we? using (IDbConnection connection = new SqlConnection(connectionString)) { connection.Open(); string dbName = connection.Database; // Voila! The database name is served! }

Parsing and assigning connection string details

Our friendly SqlConnectionStringBuilder separates connection string parameters so you don't have to. Talk about a valuable friendship!

var builder = new SqlConnectionStringBuilder(); builder.ConnectionString = "Server=myServerAddress;...;"; // Organized access to details string serverName = builder.DataSource; // The server name, at your service! bool isSecurityIntegrated = builder.IntegratedSecurity; // Are we secure here? Let's check!

Master the connection string syntax and leverage the SqlConnectionStringBuilder to make your database connectivity tasks a breeze.