Introduction
When you are programming managed code that needs to access some SQL database, you need to provide a connection string. In many cases, you have to build it manually, store somewhere, and allow user to change some of the components of this connection string. To help you especially with the latter task, I provide you this (very simple, indeed) C# class.
This class accepts all valid SQL connection string value names and its content (for currently used values). You can review them at MSDN.
Using the code
public class SqlConnectionString : ICloneable
{
public string ConnectionString {get;set;}
public string Server {get;set;}
public string Database {get;set;}
public string UserID {get;set;}
public string Password {get;set;}
public bool Authentication {get;set;}
}
SqlConnectionString
class has six public properties:
ConnectionString
- sets or gets whole connection string. When there is no database nor server specified, returned connection string is empty.
Server
- The name or network address of the instance of SQL Server to which to connect.
Database
- The name of the database.
UserID
- The SQL Server login account. Valid when not using Windows Integrated Security.
Password
- The password for the SQL Server account logging on. Valid when not using Windows Integrated Security.
Authentication
- When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
You can set any valid SQL connection string to ConnectionString
property. When you then read this property, you will get always the same value names. I.e., you can set "Trusted_Connection=yes" or "Trusted_Connection=true" or "Integrated Security=true", but you will always get "Integrated Security=SSPI".
SqlConnectionString connStr = new SqlConnectionString();
connStr.ConnectionString =
"Trusted_Connection=yes;Addr=MyServer;Initial Catalog=MyDatabase";
connStr.Server = txtServer.Text;
connStr.Database = txtDatabase.Text;
try
{
using (SqlConnection connection =
new SqlConnection (connStr.ConnectionString))
{
}
}
This class also implements ICloneable
, so you can clone your connection string, and modify its copy separated from the cloned object.
History
Posted on 15th September 2004.