el_figurin
el_figurin

Reputation: 13

How can I have the SQL connection string in one place?

Currently I have the SQL connection string in every form in my application, like this:

Dim cnx As New SqlConnection("Server = SERVERNAME\SQLSERVEREXPRESS; " &
                             "Database = DatabaseName; " &
                             "Trusted_Connection = True;")
Dim cmd As SqlCommand
Dim sdr As SqlDataReader

The problem is when I need to change it, I have to do it in every form in the application. What are some better ways to do this?

Thanks!

EDIT

I ended up using Christopherous 5000 answer translated to VB.NET:

Public Shared Function GetConnectionString(name As String) As String
    Dim connectionString = ConfigurationManager.ConnectionStrings(name)

    If connectionString Is Nothing OrElse String.IsNullOrEmpty(connectionString.ConnectionString) Then
        Throw New ConfigurationErrorsException(String.Format("No connection string for '{0}' found", name))
    End If

    Return connectionString.ConnectionString
End Function

Upvotes: 0

Views: 1071

Answers (2)

Christoph
Christoph

Reputation: 4401

You should use the web.config file to store connection string (these can be encrypted if needed)

I use a helper class with this static method when needing a connection;

public static string GetConnectionString(string name)
        {
            var connectionString = ConfigurationManager.ConnectionStrings[name];

            if (connectionString == null || string.IsNullOrEmpty(connectionString.ConnectionString))
                throw new ConfigurationErrorsException(string.Format("No connection string for '{0}' found", name));

            return connectionString.ConnectionString;
        }

Upvotes: 1

Jason Hughes
Jason Hughes

Reputation: 778

App.config or Web.config depending on project would make sense. If you won't be keeping your compiled code private than you'd want to bake your own implementation. Accessing database connection string using app.config in C# winform

Upvotes: 0

Related Questions