Categories
Asp, Asp.net

How to Create Database Connection in Asp.Net

How to Create Database Connection in Asp.Net

To make dynamic website,portals and online application, we require database (SQL Server,Access,MySQL,Oracle) etc.

To create a database connection in asp.net follow the following steps:-

1. By using Web.config:-

(i) Go to your web.config file and then locate the <connectionStrings/>.

Change it like this:-

<connectionStrings>                              
<add name="con" connectionString="Data Source=.; Initial Catalog=test;Integrated Security=True"/>
</connectionStrings>

in this Data Source stand for server where your database resides. . stand for local server. Initial catalog stand for database name.

(ii)  Now come to your coding page(demo.aspx.cs) .

Add the following Namespace :-

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

Now initialize connection on page_load or button click event wherever you want.

string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString; SqlConnection conn = new SqlConnection(strcon);
conn.open();

2. Directly on code file.

Add the following Namespace :-

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

SqlConnection con = new SqlConnection("Server=Youserver name or comp name;Database=databasename;Trusted_Connectopn=True"); SqlCommand cmd = new SqlCommand("Write your sql query here eg. select * from Table name");   
con.Open();

To use Microsoft Access database make connection-string like this:-

Add following Namespace:-

using System.Data.OleDb;

Now on page_load or on button click event use this:-
OleDbConnection con = new OleDbConnection();
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path of your .mdb file");
con.open();

Enjoy:)