Connection string form Web.config/App.Config using c#

Bangalore: To establish connection with database we need to declare the connection string. where ever you are making an operation with database you need to open the connection with db and you have to make the transaction. so its not good idea to use the connection string details in each page. It will affect he codes optimization/security etc.
so you can declare your connection strings inside the web.config file and you can return a common method to retrieve/return the connection string.


<configuration>
<connectionStrings>
    <add name="localhost" connectionString="Server=localhost; Database=TestDB; User ID=SqlAdmin; Password=TestPwd;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"/>
  </connectionStrings>
</configuration>

Now we are going to write a method which will return the connection string. we can use it in a common page and we can re-use it in our pages depends on your requirement.


    public static String GetConnectionString
        {
            get { return ConfigurationManager.ConnectionStrings["localhost"].ConnectionString; }

        }


0 comments: