Thursday, February 6, 2014

Database Connection in ASP.NET C# Connection String

Database is an integral part of any websites. Its the main part of the whole web technology. So we have to take it with a little bit extra care.... :P

So in this article We are going to watch how to connect your database with your ASP.NET application.

In your application you there is a file called web.config where we have to write our connectionString. You can find it from Solution Explorer. If you didn't find the Solution Explorer then don't worry, here is the path to open Solution Explorer.

View -> Solution Explorer. or press Ctrl+W,S.





Now find the web.config file in your solution explorer and open it. Those who have worked with htaccess, this file something like that.

Its basically a XML file, with full of XML tags and nothing else. You can check it by this line at the top of the file.   <?xml version="1.0"?>

Now in this file within the <configuration> tag we have to write every thing that we want to attach with this application like DB connection or session time out or errors like 404, 403 etc..

For each and every thing there is different tags defined.

For Database we need the tag named  <connectionStrings> within <configuration> tag. And within this tag add a key value and the propoer connection string.

<configuration>
  <connectionStrings>
    <add name="<add a name here>" connectionString="Data Source=<Server name>; Initial Catalog = <Your Database name>; Trusted_Connection=True"/>
  </connectionStrings>
</configuration>


Now add a name according to you in name section 
Within the connectionString ---
Data Source : Server name(Your Computer name or Remote server name or IP address;  Ex: WIN-ArkaPc/SQLEXPRESS or 192.168.0.1) 
Initial Catalog : Database name
Trusted_Connection : make it True
uid : User id of your database
password : password of your user id
AttachDbFilename : |DataDirectory|dbfile.mdf (Attach database from any .mdf  file)

Now how to connect it with your application. Very simple..

In a class file add two namespaces.

using System.Web.Configuration;
using System.Data.SqlClient;


And now add this line in the class file globally, so every methods of the class can use this connection.

SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["<Your name value>"].ToString());

Now using this you can do every database operation in your application and add this code in every class file where database connection is required or you can make a file named connection.cs where this code will be there you just create an instance to use this or you can inherit this file to do your functionalists.

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews