Sql Connection by Creating DataContext Layer

Before Creating Any Application In asp.net with database we need to create connection between database and application i always use datacontext class to establish connection between application and sql.

you can download datacontext class from below!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class DataContext
{

SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();

public void Openconnection()
{
if (con.State == ConnectionState.Closed)
{
try
{

// connection string change data source database name username and password
string constring = “Data Source=.; Initial Catalog=databasename; Integrated Security=True”;
con.ConnectionString = constring;
con.Open();
cmd.Connection = con;
}
catch (Exception ex)
{
ex.Message.ToString();
}

}

}
public void CloseConnection()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
public DataTable getDataTable(string Query)
{
DataTable dt = new DataTable();
Openconnection();
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
da.SelectCommand = cmd;
da.Fill(dt);
CloseConnection();
return dt;
}
public int executeNonquery(string Query)
{
Openconnection();
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
int i = cmd.ExecuteNonQuery();
CloseConnection();
return i;
}

}

you can use this class as it is in your every windows or web applications.
its very simple and easy to create connection with this class…

click on file icon!

Download

Leave an Awesome Comment

comments

No comments.

Leave a Reply