Building a Connection String at Runtime

Posted Fri, May 28 2010 17:54 by Deborah Kurata

There are some scenarios that require building a connection string at runtime. For example, if you are building a database utility or if your application allows working with multiple databases. In these cases, you may want to ask the user for the basic parts of the connection and not require entry of a syntactically correct connection string.

Here is an example of a Windows Forms dialog for entry of connection information:

image

(Thanks to my friend Robin for creating this nice user interface.)

After the user makes the appropriate selections, you can use the entered values to create a connection string.

The xxxConnectionStringBuilder classes in System.Data can help you with this. Use the SqlConnectionStringBuilder class if you are accessing SQL Server or the OdbcConnectionStringBuilder class if you are referencing a Microsoft Access or other Odbc database.

This example uses the SqlConnectionStringBuilder. But you can readily replace it with OdbcConnectionStringBuilder when necessary.

The following example defines a shared/static function that builds a connection string from the controls on the form shown above.

Be sure to set a reference to System.Data.SqlClient.

In C#:

private static string CreateConnectionString()
{
    SqlConnectionStringBuilder sqlBuilder =
                          new SqlConnectionStringBuilder();

    if (!string.IsNullOrWhiteSpace(ServerNameTextBox.Text)) {
        sqlBuilder.DataSource = ServerNameTextBox.Text;

        if (!string.IsNullOrWhiteSpace(DatabaseNameComboBox.Text) {
            sqlBuilder.InitialCatalog = DatabaseNameComboBox.Text;
        }

        sqlBuilder.IntegratedSecurity = 
                      AuthenticationComboBox.SelectedValue ==
                      AuthenticationType.Windows ? true : false;

        // For SQL Server authentication, need a user Id and password
        if (sqlBuilder.IntegratedSecurity == false) {
            sqlBuilder.UserID = UserIdTextBox.Text;
            sqlBuilder.Password = PasswordTextBox.Text;
        }
    }
    return sqlBuilder.ConnectionString;
}

In VB:

Private Shared Function CreateConnectionString() As String

    Dim sqlBuilder As New SqlConnectionStringBuilder

    If Not String.IsNullOrWhiteSpace(ServerNameTextBox.Text) Then
        sqlBuilder.DataSource = ServerNameTextBox.Text

        If Not String.IsNullOrWhiteSpace(DatabaseNameComboBox.Text) Then
            sqlBuilder.InitialCatalog = DatabaseNameComboBox.Text
        End If

        sqlBuilder.IntegratedSecurity = If
                          (AuthenticationComboBox.SelectedValue =
                           AuthenticationType.Windows, True, False)

        ' For SQL Server authentication, need a user Id and password
        If sqlBuilder.IntegratedSecurity = False Then
            sqlBuilder.UserID = UserIdTextBox.Text
            sqlBuilder.Password = PasswordTextBox.Text
        End If
    End If

    Return sqlBuilder.ConnectionString
End Function

NOTE: The above code uses the implicit line continuation feature that is new in VB 10 (VS 2010). If you have an older version of VB, you will need to add the line continuation character ( _ ) where necessary.

The CreateConnectionString function shown above creates a new instance of the SqlConnectionStringBuilder. It then assigns the properties of the SqlConnectionStringBuilder from the data entry fields. The ConnectionString property then contains the appropriate connection string.

You can then use the returned connection string to connect to the selected database.

Enjoy!

Filed under: , , , ,

Comments

# re: Building a Connection String at Runtime

Sunday, May 30, 2010 10:03 AM by Luciano Evaristo Guerche (Gorše)

Deborah,

Do you know whether there is a managed "Microsoft OLEDB Service Component 1.0 Type Library" so that one could code similar to "HOW TO: Build a Connection String Programmatically in ADO.NET by Using Visual C# .NET" support.microsoft.com/.../310083 without having to resort to interoperability wrappers?

Regards,

# re: Building a Connection String at Runtime

Sunday, May 30, 2010 1:22 PM by Deborah Kurata

Hi Luciano -

Do you have to use OleDb? Most databases are accessible using Odbc.

# re: Building a Connection String at Runtime

Wednesday, June 02, 2010 8:25 AM by Rostov

Yeah, I used to have a wrapper for connection strings on my own until I found the XXXConnectionBuilders one day and was really impressed with how easy they were to use.

Thanks again for your articles Deborah!

# re: Building a Connection String at Runtime

Wednesday, February 08, 2012 12:43 PM by glemer

C# OLEDB connection strin sample

csharp.net-informations.com/.../csharp-oledb-connection.htm

glemer

# re: Building a Connection String at Runtime

Monday, February 27, 2012 5:36 AM by Ali

Thanks for this code,

Can I download this form with soure code?

Please..

Best regards

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: