Read
Boolean moreRecords = DataReader.Read();
Moves to the next record. If no record can be found, it returns
false
. Otherwise, it returns
true
. When the DataReader
is
first created, it is positioned just before the first row. You must
call Read( )
before you can retrieve information
from the first row. (The first Read( )
call
advances the DataReader
to the first record, if
any.)
The following code shows the basic pattern of access for reading rows
with the DataReader
. The Read( )
method is invoked as part of a while
loop, ensuring that the loop ends immediately when the Read( )
method returns false
.
string SQL = "SELECT ContactName FROM Customers"; SqlCommand cmd = new SqlCommand(SQL, con); SqlDataReader r; try { con.Open(); r = cmd.ExecuteReader(); // Iterate over the results. while (r.Read()) { Console.WriteLine(r["ContactName"].ToString()); } } finally { con.Close(); }
Because the DataReader
encapsulates a live
connection, you should read all the information as quickly as
possible and close the connection immediately after.