Multiple connection strings

charlie20

Member
Joined
Aug 27, 2012
Messages
11
Programming Experience
Beginner
I have a winforms application & depending on the user selection regarding SQL authentication there are 2 possible connection strings :-

- using (var con = new SqlConnection(String.Format("Data Source={0}; database={1}; Integrated Security=True", Sql_ServerName, Sql_DataBaseName)))
- using (var con = new SqlConnection(String.Format("Data Source={0}; database={1}; User id={2}; Password={3};", Sql_ServerName, Sql_DataBaseName, txt_SqlAuth_UserName.Text, txt_SqlAuth_Password.Text)))

First one is for windows authentication with the second being a facility for entering a specific username/password for the SQL server (sa for example).

Apart from these con strings the remainder of the code is the same. How can I do an IF/THEN type statement depending on which selection the user has made??

I have attempted an IF/THEN & also declaring the var con in the variables block, both without success.

Any tips, pointer etc?
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,052
Location
Sydney, Australia
Programming Experience
10+
Don't use String.Format for connection strings. Each ADO.NET provider has a connection string builder class for manipulating connection strings. In your case, I'd make the one using integrated security the default connection string and then make changes if and only if the user selects otherwise, e.g.
var builder = new SqlConnectionStringBuilder();

builder.DataSource = dataSource;
builder.InitialCatalog = initialCatalog;
builder.IntegratedSecurity = useIntegratedSecurity;

if (!useIntegratedSecurity)
{
    builder.UserID = userID;
    builder.Password = password;
}

using (var connection = new SqlConnection(builder.ConnectionString))
{
    // Use connection here.
}
 
Top Bottom