SqlDataReader.Read Method
Advances the SqlDataReader to the next record.
Assembly: System.Data (in System.Data.dll)
The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data.
Only one SqlDataReader per associated SqlConnection may be open at a time, and any attempt to open another will fail until the first one is closed. Similarly, while the SqlDataReader is being used, the associated SqlConnection is busy serving it until you call Close.
The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it out to the console window. The code then closes the SqlDataReader. The SqlConnection is closed automatically at the end of the using code block.
private static void ReadOrderData(string connectionString) { string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); // Call Read before accessing data. while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } // Call Close when done reading. reader.Close(); } }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
It states :
"true if there are more rows; otherwise false"
The fact is that the example provided is correct, but the previous statement is paradoxiacal : if you call Read() and it returns false, you must NOT try to extract data from your SqlDataReader. However the statement looks like you must read it, but the very next one will fail.
It should read :
"true if there was a row; false otherwise"
Because if you try reading just after it returned false, it throws an exception.
- 1/27/2012
- Mish-Yoshi