Traverse Records in a data reader
When the ExecuteReader method returns a DataReader object, the position of the current cursor precedes the first record .
The Read method of the reader must be called to move the cursor to the first record, and then the first record becomes the current record.
If the data reader contains more than one record, the Read method returns a Boolean value of true.
To move to the next record, you need to call the Read method again. Repeat the process until the last record, at which time the Read method returns FALSE.
Often use the while loop to traverse Records:
while (reader. Read ())
{
Reading data
}
As long as the Read method returns a value of True, you can access the fields contained in the current record.
Accessing values in a field
Ado. NET provides two ways to access fields in a record.
The first is the Item property, which returns the field value specified by the field index or field name.
The second method is the Get method, which returns the value of the field specified by the field index.
The DataReader class has an index character that can access any field using common array syntax.
Using this method, you can access the value of a particular column either by specifying the name of the data column or by specifying the number of the data column.
The first column is numbered 0, the second column number is 1, and so on. For example:
Object value1=mydatareader["learning number"];
Object Value1=mydatareader[0];
Item Properties
Each of the DataReader classes defines an item property that returns an object for a Code field property.
The Item property is the index of the DataReader class.
It is important to note that the Item property is always numbered based on 0:
Object Fieldvalue=reader[fieldname];
Object Fieldvalue=reader[fieldindexl;
You can pass a string that contains a field name to the Item property, or a 32-bit integer that specifies the field index to the Item property.
For example, if the command is a SQL SELECT query:
Select ID, CName from course
You can get the values of two returned fields using either of the following methods:
Object Id=reader ["ID"]
Object Cname=reader ["CName"];
Or:
Object Id=reader[0];
Object Cname=reader [1];
It is also important to note that you need to be responsible for type conversions when working with data, as follows:
int id= (int) reader[0];
String Cname= (String) reader[1];
Note: If a type conversion error, such as converting a non-numeric type to an integral type, throws an exception at run time.
Get Method
In addition to accessing data through an index, the DataReader class has a set of type-safe access methods that can be used to read the values of a specified column.
These methods start with get, and their names are self-explanatory.
such as GetInt32 (), GetString (), and so on.
These methods all have an integer parameter that specifies the number of the column to read.
Each of the DataReader classes defines a set of Get methods that return values of the appropriate type.
For example, the GetInt32 method takes the returned field value as a 32-bit integer.
Each get method accepts the index of the field,
For example, in the example above, you can retrieve the value of the ID field and the CNAME field using the following code:
int Id=reader. Getint32 (0);
String Cname=reader. GetString (1);
Example Demo DataReader
In this example, all the student information is read and displayed.
(1) Start visual Studio and create a new WindowsApplication project named Datareadertest.
(2) Double-click the mouse in the blank of Forml.cs to enter the Page-load event. The Page_Load event is executed when the page loads.
(3) First add the SqlClient namespace to the Forml.cs:
Using System. Data. SqlClient;
(4) Add the following code to the Page_Load event:
usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Data.SqlClient;namespacedatareadertest{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Private voidForm1_Load (Objectsender, EventArgs e) { //Defining output Messages stringMessage=""; //New Connection ObjectSqlConnection conn=NewSqlConnection (); Conn. ConnectionString="Data source= (local); Initial catalog=student;integrated Security=sspi"; //Stitching Command String stringselectquery="Select ID, sname,sgrade,ssex from Studentinfo"; //new Command ObjectSqlCommand cmd=NewSqlCommand (SelectQuery, conn); Conn. Open (); //The database connection is closed automatically when you close the readerSqlDataReader reader=cmd. ExecuteReader (commandbehavior.closeconnection); //cyclic reading of information while(reader. Read ()) {message+="School Number:"+reader[0]. ToString () +" "; Message+="Name:"+reader["SName"]. ToString () +" "; Message+="class:"+reader. GetString (2)+" "; Message+="Gender:"+reader. GetString (3)+" "; Message+="\ n"; } //turn off the data reader//no need to close the connection, it will be shut down automaticallyReader. Close (); //test whether the data connection has been closed if(Conn. state==connectionstate.closed) {message+="The data connection is closed \ n"; } messagebox.show (message); } }}
C # and database Access Technology Summary (12) data Reader (DataReader) 2