ADO.NET

ADO.NET Projects

ADO.NET Project 1

ADO.NET Examples

Examples

adplus-dvertising
Read Data from table using OleDBDataReader
Previous Home Next
protectedvoidPage_Load(objectsender,EventArgse)
{
//ConnectionString
OleDbConnectionNewConnection=new
OleDbConnection
(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=D:\newDtabse.mdb");
NewConnection.Open();//ConnectionOpen
//CommandQuery
OleDbCommandcmd=newOleDbCommand
("Select*fromemp_tbl",NewConnection);
OleDbDataReaderdr=cmd.ExecuteReader();
if(dr.HasRows)
{
GridView1.DataSource=dr;//UsingGridViewtoShowthedata.
GridView1.DataBind();
}
NewConnection.Close();//ConnectionClose
}
To read data from Access database using an OleDbCommand object
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
//ConnectionString
OleDbConnectionNewConnection=new
OleDbConnection
(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=D:\newDtabse.mdb");
OleDbCommandcmd=NewConnection.CreateCommand();//CreatingCommandObject
cmd.CommandText="select*fromemp_tbl";//CommandText
NewConnection.Open();//ConnectionOpen
OleDbDataReaderdr=cmd.ExecuteReader();
if(dr.HasRows)
{
GridView1.DataSource=dr;//UsingGridViewtoShowthedata.
GridView1.DataBind();
}
NewConnection.Close();//ConnectionClose
}
}
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();
}
}
Previous Home Next