Saturday, May 24, 2008

The SqlConnectionStringBuilder Class

One of the more handy BCL (Base Class Library) features that I ran across years ago, but don't think has gotten much attention is the SqlConnectionStringBuilder class that resides in the System.Data.SqlClient namespace.  This is such a handy class, as it allows you to forget about the proper syntax of the connection string, and just let you deal with the parts that seem necessary.  No asking yourself "is it Trusted Security or Integrated Security???".  Well, maybe you have an easier time with it than I do, but, still a handy class.

It's also super handy if you've got your connection string as a string, and you need parts of it.  No need to write your own parsing.  Just load it up into the SqlConnectionStringBuilder class and get the parts you need from the properties of the class.

Below is a simple sample, there's obviously much more to it as far as connection string options, but I'll let you explore those on your own.

SqlConnectionStringBuilder builtFromScratch = new SqlConnectionStringBuilder();
builtFromScratch.DataSource = "(local)";
builtFromScratch.InitialCatalog = "MyDatabase";
builtFromScratch.IntegratedSecurity = true;
SqlConnectionStringBuilder builtFromString
    = new SqlConnectionStringBuilder(builtFromScratch.ToString());
Console.WriteLine("Server: {0}", builtFromString.DataSource);
Console.WriteLine("Database: {0}", builtFromString.InitialCatalog);
Console.WriteLine("Windows Authentication: {0}", builtFromString.IntegratedSecurity);