Read Data from table using OleDBDataReader
protected void Page_Load(object sender, EventArgs e)
{
//Connection String
OleDbConnection NewConnection = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb");
NewConnection.Open();//Connection Open
//Command Query
OleDbCommand cmd = new OleDbCommand("Select * from emp_tbl", NewConnection);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
GridView1.DataSource = dr; //Using GridView to Show the data.
GridView1.DataBind();
}
NewConnection.Close();// Connection Close
}
|
To read data from Access database using an OleDbCommand object
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Connection String
OleDbConnection NewConnection = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb");
OleDbCommand cmd = NewConnection.CreateCommand();//Creating Command Object
cmd.CommandText = "select * from emp_tbl";//Command Text
NewConnection.Open();//Connection Open
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
GridView1.DataSource = dr; //Using GridView to Show the data.
GridView1.DataBind();
}
NewConnection.Close();// Connection Close
}
}
|
ExecuteScaler
- ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution.
- It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set.
- If the Result Set is empty it will return a Null reference.
- It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection NewConnection = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb");
OleDbCommand cmd = NewConnection.CreateCommand();
cmd.CommandText = "select count(*) from emp_tbl";
NewConnection.Open();
int count =(int)cmd.ExecuteScalar();
Label1.Text = count.ToString();
}
}
|
No comments:
Post a Comment