ConnectionString
string connectionString
= Connection.ConnectionString;
Returns or sets a string that opens a database connection. The connection string is formatted as a collection of name/value pairs separated by semicolons. These settings can be provider-specific but typically follow certain conventions; they include basics such as the source database name, the location of the database server, and login information. The connection string is case-insensitive, and all blank characters are ignored.
The first example creates a SqlConnection
that
accesses a database on the local computer. Some properties of the
connection string are set to connect to the Northwind database using
integrated security.
SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source = localhost;" + "Integrated security = SSPI;Initial Catalog = Northwind";
The following example creates an OleDbConnection
.
Some properties of the connection string are set to connect to the
Northwind database, using integrated security. Note that the
information is identical, except for the addition of a
Provider
setting that specifies what underlying
OLE DB provider should be used.
OleDbConnection conn = new OleDbConnection(); Conn.ConnectionString = "Provider = SQLOLEDB;Data Source = localhost;" + "Integrated Security = SSPI;Initial Catalog = northwind";
The ConnectionString
property can be set only when
the connection is closed. The Connection
class
provides many read-only properties that correspond to individual
pieces of information from the connection string.
Values in the connection string can optionally be delimited by single
or double quotes, e.g., name='value'
or
name="value"
). The most common reason to
use this approach is when you need to include blank or semicolon
characters in a connection string value.
Any variation in a connection string can thwart connection pooling, so be sure to draw connection strings from a fixed location such as a configuration file to ensure consistency, rather than place them directly in code or construct them manually.
When retrieving the ConnectionString
property, you
will find that the user authentication information is automatically
removed, unless you specifically submit the
Persist
Security
Info
setting in the connection string with a value
of true
.
For a full list of connection string settings and examples of various provider-specific connection strings, see Chapter 3.