Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if it's the last record in sqldatareader

Is there a way to check if I'm on the last record ? thanks

like image 547
wben Avatar asked Jul 28 '12 17:07

wben


People also ask

Is it necessary to manually close and dispose of SqlDataReader?

You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

Is there anything faster than SqlDataReader in net?

SqlDataReader is the fastest way. Make sure you use the get by ordinal methods rather than get by column name. e.g. GetString(1);

Which of the following property of SQL data reader class is used to check if SqlDataReader has rows?

The HasRows property may help you. Type: System. Boolean true if the SqlDataReader contains one or more rows; otherwise false. Save this answer.


2 Answers

Use this pattern to identify and process the last row in result:

if (reader.Read())
{
    var loop = true;
    while (loop)
    {
        //1. Here retrive values you need e.g. var myvar = reader.GetBoolean(0);
        loop = reader.Read();
        if (!loop)
        {
            //You are on the last record. Use values read in 1.
            //Do some exceptions
        }
        else {
            //You are not on the last record.
            //Process values read in 1., e.g. myvar
        }
    }
}
like image 92
Raman Zhylich Avatar answered Oct 03 '22 05:10

Raman Zhylich


Other than "there isn't another one afterwards", no. This may mean you need to buffer the row, try to read, then look at the buffered data if it turned out to be the last.

In many cases, when the data is moderate and you are building an object model of some kind, you can just looks at the constructed data, i.e. make a List<T> of all the rows when using the reader, then after that, look at the last row in the list.

like image 42
Marc Gravell Avatar answered Oct 03 '22 05:10

Marc Gravell