Today I found, that storing connection strings were little bit changed between .NET 2.0 and .NET 3.5.
Here is an example of how to store a database connection string in the application’s Web.Config file for .NET 2.0. The code for accessing the connection string is located in the C# code below.
.NET 2.0
<appSettings>
<add key="ConnectionString" value="server=localhost;database=TestDB;uid=sa;password=secret;" />
</appSettings>
And here is the C# code how to get it.
using System.Configuration;
public class TestGetConnection
{
public TestGetConnection()
{
try
{
// Get connection string from Web.Config
string strConnection = ConfigurationSettings.AppSettings("ConnectionString");
}
}
}
.NET 3.5
ConfigurationSettings.AppSettings is now deprecated.
<connectionStrings>
<add name="YourConnectionString" connectionString="server=localhost;database=TestDB;uid=sa;password=secret;" providerName="System.Data.SqlClient" />
<add name="NewString" connectionString="server=localhost;database=TestDB;uid=sa;password=secret;" providerName="System.Data.SqlClient" />
</connectionStrings>
And here is the C# code how to get it.
using System.Configuration;
public class TestGetConnection
{
public TestGetConnection()
{
try
{
// Get connection string from Web.Config
string strConnection = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
}
}
}
You can use <remove /> to delete connection setting from web.config.
<connectionStrings>
<remove name="YourConnectionString"/>
<add name="YourConnectionString" connectionString="server=localhost;database=TestDB;uid=sa;password=secret;" providerName="System.Data.SqlClient" />
</connectionStrings>
Connection String Syntax Notes
- Values may be delimited by single or double quotes, (for example, name=’value’ or name=”value”). Either single or double quotes may be used within a connection string by using the other delimiter, for example, name=”value’s” or name=’value”s’,but not name=’value’s’ or name=”"value”". The value type is irrelevant.
- All blank characters, except those placed within a value or within quotes, are ignored.
- Keyword value pairs must be separated by a semicolon ( ; ). If a semicolon is part of a value, it also must be delimited by quotes.
- Names are not case sensitive. If a given name occurs more than once in the connection string, the value associated with the last occurence is used.
- No escape sequences are supported.
If you need to connect to SQL Express, you shold use connection string with specifying the file you want to attach.
connectionString="Server=.\SQLExpress;AttachDbFilename=c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\SpamTestimonial.mdf;Database=SpamTestimonial;Trusted_Connection=Yes;"
If you need to find all possible connection string, go to web page dedicated to them for more databases than you can image. http://www.connectionstrings.com/
.NET
.NET, C#, Connection String, Database, SQL