I am a beginner in ASP. Please help me in this simple concept. How to store a connection string in web.config and how to make use of it in in ADO.NET while connecting to SQL 2008 DB?
2 Answers
Hi please check the code below:
In Asp.Net 2.0
You can add a key inside appSettings.
<appSettings>
<add key="ConnectionStringName" value="server=localhost; database=DatabaseName; uid=SqlInstanceUserName; password=SqlInstancePassword;" />
</appSettings>
To read the connection string:
string connStr = ConfigurationSettings.AppSettings("ConnectionStringName");
In Asp.Net 3.5
You can add a key inside connectionStrings.
<connectionStrings>
<add name="ConnectionStringName" connectionString="server=localhost; database=DatabaseName; uid=SqlInstanceUserName; password=Sq lInstancePassword;" />
</connectionStrings>
To read the connection string:
string connStr = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
Comments
This SO answer has some good pointers about connection strings. How to define a connection string to a SQL Server 2008 database?. This MSDN documentation http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx has information about connection strings and examples also in the configuration files.