This article explains the basic details of ADO.NET Part 2.
Read here my first article of ADO.NET Part 1:
Introduction To ADO.NET
The methods of the Command Class are:
- Executer Reader()
- ExecuteScaler()
- ExecuteNonQuery()
Note: After creating an object of the command class we need to call any of these 3 methods to execute the statements.
Let's see the details of all these methods.
1. Call ExecuteReader ( )
The method when we want to execute a “Select statement” that returns data as rows and columns. The method returns an object of the Data Reader class that contains data retrieved from a Data Source in the format of rows and columns.
2. Call ExecuteScaler ( )
The method when we want to execute a “Select Statement ” that returns a “single” value result. The method returns the results of the query in the form of an object.
3. Call ExecuteNonQuery
This method call when we want to execute any statement other than a select, like insert, update, delete, and so on. This method returns a numeric value telling the number of rows affected by the statements.
Accessing Data From DataReader
DataReader is a class that holds data as rows and columns to access data from the DataReader.
It provides the following methods:
- GetName(int ColIndex)
The return type of this method is a string, it returns the name of the column for the given index position.
- Read()
Moves the Record Pointer from the current location to the next row and returns a Boolean status that tells whether the row to which we have moved contains data in it or not, that will be true if present or false if not present.
- GetValue(int Colindex)
Returns a column's value from the row to which the pointer was pointing by specifying the column index position.
- NextResult ()
Moves the record pointer from the current table to the next table if a table exists and returns true else returns false.
Features of Data Reader
- Provides faster access to data from a Data Source, since it is connection-oriented
- It can hold multiple tables at a time. To load multiple tables into a DataReader pass multiple select statements as the argument to the command separated by a colon (;)
For example:
- Command cmd=new Command(“Select * From Student ; Select * From Mark ”, Con);
- Data Reader dr= cmd.ExecuteReader();
Note: use the “NextResult()” method of the DataReader object to navigate from the current table to the next table.
For example:
Dr.NextResult();
Drawbacks of DataReader:
- Connection-Oriented classes require a continuous connection with the Data Source to access the data, so the performance is decreased if there are a number of clients accessing the data at the same time.
- It gives only forward direction access to data, in other words, it allows going to the next record of the table but not to the previous record of the table.