Thursday, August 06, 2009

ConnectionStringBuilders


Connection string is a string variable which include many properties and values (InitialCatelog, uid, pwd , Data Source) needs to connect to a database.

SqlConnection cn = new SqlConnection();
cn.ConnectionString ="uid=sa;pwd=Initial Catalog=ADO; Data Source=(local); ConnectTimeout = 30";
cn.Open();

Creating connection string is bit tedious as it’s a string and could be error prone.

ADO.Net providers support connection string builder objects which allow you to create connection string , and establish the name/value pairs using strongly typed properties.

SqlConnectionStringBuilder cnStrBuilder = new SqlConnectionStringBuilder();
cnStrBuilder.UserID = "sa";
cnStrBuilder.Password = "";
cnStrBuilder.InitialCatalog = "ADO";
cnStrBuilder.DataSource = "(local)";
cnStrBuilder.ConnectTimeout = 30;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = cnStrBuilder.ConnectionString;

Here on above example , creates a SqlConnectionStringBuilder variable and passing values for
ConnectionStringBuilder properties and then the ConnectionStringBuilder’s ConnectionString value been assigned to cn.ConnectionString instead directly passing ConnectionString string
as follows.

cn.ConnectionString ="uid=sa;pwd=Initial Catalog=ADO; Data Source=(local); ";

0 comments:

My Achievements

Member of

Blog Archive

Followers