Introduction
In this
article we are going to learn the topic of writing the different type of
connections to the database for using the asp.net c#
- One method is used for the basic connection using with SqlConnection class
- And another method with DbConnection class
Coding
Steps
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Simple
Method:-
public static string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
//Accessing the connection string from the
Web.config file
SqlConnection con = new
SqlConnection(connectionString);
SqlCommand cmd = new
SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.
Text;
cmd.CommandText = "Select
* from EmployeeDetails";
SqlDataAdapter da = new
SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new
DataTable();
da.Fill(dt);
Another
Method
using System.Data.Common;
using System.Configuration;
using System.Data;
private static readonly DbProviderFactory
factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
private static readonly string
connectionStringName = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString();
public DataSet
Connection()
{
using (DbConnection
con = factory.CreateConnection())
{
con.ConnectionString = connectionStringName;
con.Open();
using (DbCommand
cmd = factory.CreateCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from
EmployeeDetails";
using (DbDataAdapter
da = factory.CreateDataAdapter())
{
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
}
No comments:
Post a Comment