Wednesday, October 9, 2013

Use SqlConnectionStringBuilder

The following code shows how to use SqlConnectionStringBuilder to conveniently construct the connection string to connect to MS SQL Server (Default SQL Server instance is assumed)


public static void RunUT_Connection()
{
 SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
 sb.DataSource = @".\SQLEXPRESS";
 sb.InitialCatalog = "mixertruck";
 sb.UserID = "[username]";
 sb.Password = "[password]";
 string connection_string = sb.ToString();
 Console.WriteLine(connection_string);
 try
 {
  using (SqlConnection conn = new SqlConnection(connection_string))
  {
   conn.Open();

   conn.Close();
  }
 }
 catch (Exception ex)
 {
  Console.WriteLine(ex.ToString());
 }
}

No comments:

Post a Comment