Using SqlConnectionStringBuilder class in C#


Microsoft introduced a new class in ADO.NET 2.0 version which can be used to build database connection strings specific to the provider you are using in ADO.NET. Different database providers expose different properties for the connection strings. For example, SQL Server connection string properties are different than MySql or OleDb connection strings. Although, it is possible to concatenate strings to build a complete connection string but by using .NET connection string builder class you don't need to memorize the properties appropriate to specific provider.

In the following tutorial, I will show you how you can use SqlConnectionStringBuilder class available in System.Data.SqlClient namespace to build a simple connection string.

SqlConnectionStringBuilder

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); 

builder.DataSource = TextBox1.Text;
builder.InitialCatalog = TextBox2.Text;
builder.UserID = TextBox3.Text;
builder.Password = TextBox4.Text; 

TextBox5.Text = builder.ConnectionString;​

Other than above mentioned four basic properties SqlConnectionStringBuilder also provides following common properties which can be used to build connection string with more options.
AsynchronousProcessing

AttachDBFilename
IntegratedSecurity
MaxPoolSize
MinPoolSize
MultipleActiveResultSets
PacketSize
Pooling
UserInstance
WorkstationID

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments 4

user
Huma
  • 11 March 2009

sir
i want to know that how to use Datalist control . Actually i want to show the category list through db .

user
Nice Guy
  • 07 September 2009

I want to know, How can I check that "file or file path" is correct before opening the connection. So that exception may not accur.

Waqas Anwar
Waqas Anwar
  • 07 September 2009

string filePath = "C:\\abc.txt";
FileInto file = new FileInfo(filePath);

if(file.Exists())
{
// Process your File here.
}

user
Gentleman
  • 23 April 2010

Sir I request you, please add more in this tutorial about storing this connection string into app.config or web.config.

Add Comment