how to check if sqldatareader return any value
Here is the code i came up with::
reader = cmd.ExecuteReader();
reader.Read();
if (reader.Read())
intQ = int.Parse(reader[0].ToString());
else
intQ = 0;
txtblck.Text = intQ.ToString();
reader.Close();
But this causes it to alway开发者_如何学Pythons execute the else, and if i do this:
reader = cmd.ExecuteReader();
if (reader.Read())
intQ = int.Parse(reader[0].ToString());
else
intQ = 0;
txtblck.Text = intQ.ToString();
reader.Close();
The if always return true, how should do this?
Check the HasRows property. Perhaps this is what you're looking for (your question is quite clear to me).
if( reader.HasRows )
HasRows returns a value if the resultset contains records. Do you want to achieve that ? Or, do you want to know whether a particular field of a certain record contains a value ?
How does your SQL Statement look like ?
reader.Read()
advances the reader to the next record, where the reader is initially set to before the first record. If calling reader.Read()
returns false this means that it was unable to advance to the next record (i.e. the current record is the last record).
This means that if you wish to read the first record you need to call reader.Read()
once, and if reader.Read()
returns false it means there were no records - like so:
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
intQ = int.Parse(reader[0].ToString());
}
else
{
intQ = 0;
}
}
txtblck.Text = intQ.ToString();
FYI int.Parse
will throw an exception if the first record is null - this is different from having zero rows. Perhaps you should check for null values, or use int.TryParse
instead.
Checking the the MSDN documentation for SqlReader
reveals that is has a property called HasRows
which you can use.
if (reader.HasRows)
{
...
}
Read() gets the next row of the result set.
So if you return one row the first read gets that row and the second Read() returns false as there is no second row - so the else happens.
精彩评论