Saturday, 23 June 2012

Beginning .Net : Store and Retrieve database connection string in C# .Net Programming and VB.Net Programming

As a .Net beginners you need to know about how and where to store database connection string and how to retrieve this database connection string.
Store database connection string in Web.Config file is a good way.
In Web.Config file there is "<configuration>" section , In this section there is "<connectionStrings>" section. In this section you can add your connection string. You can add connection string using add tag.

Here are sample example of web.config file in which we store connection string.

Web.Config file :
        <add name="NorthWindConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;;User ID=sa;Password=sa;" providerName="System.Data.SqlClient"/>

In this we can set the connection string name and connection string values and provider name. In this example we set name as "NorthWindConnectionString" and provider as "System.Data.SqlClient" for SQL Sever. You can set different provider for different database servers ie ORACLE , SYBASE etc...

Now we are retrivieing this stored database connection string in our code. The easiest way to read this connection string is to use the ConnectionStrings property of the System.Configuration.ConfigurationManager class. Specify the name of the connection string you want as the property index will return a System.Configuration.ConnectionStringSettings object. You can use ConnectionString property of System.Configuration.ConnectionStringSettings object.

Here are example of read database connection string from web.config into server side code.

C# Example :
        System.Configuration.ConnectionStringSettings objConnSetting= System.Configuration.ConfigurationManager.ConnectionStrings["NorthWindConnectionString"];
        string conString = objConnSetting.ConnectionString;
        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = objConnSetting.ConnectionString;
        /////Do you database stuff
        objConn.Close(); Example :
        Dim objConnSetting As System.Configuration.ConnectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings("NorthWindConnectionString")
        Dim conString As String = objConnSetting.ConnectionString

        Dim objConn As New SqlConnection()
        objConn.ConnectionString = objConnSetting.ConnectionString
        ''''Do you database stuff

No comments:

Post a Comment