如何检查 sqldatareader 是否返回任何值
这是我想出的代码::
reader = cmd.ExecuteReader();
reader.Read();
if (reader.Read())
intQ = int.Parse(reader[0].ToString());
else
intQ = 0;
txtblck.Text = intQ.ToString();
reader.Close();
但这会导致它总是执行 else,如果我这样做:
reader = cmd.ExecuteReader();
if (reader.Read())
intQ = int.Parse(reader[0].ToString());
else
intQ = 0;
txtblck.Text = intQ.ToString();
reader.Close();
if 总是返回 true,应该怎么做?
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 always 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
检查 HasRows 属性。也许这就是您正在寻找的(您的问题对我来说很清楚)。
如果结果集包含记录,HasRows 将返回一个值。
你想实现这个目标吗?
或者,您想知道某个记录的特定字段是否包含值?
你的 SQL 语句是什么样的?
Check the HasRows property. Perhaps this is what you're looking for (your question is quite clear to me).
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()
将读取器前进到下一条记录,读取器最初设置为第一条记录之前。如果调用reader.Read()返回false,这意味着它无法前进到下一条记录(即当前记录是最后一条记录)。这意味着如果您想读取第一条记录,您需要调用一次reader.Read(),如果reader.Read()返回false,则意味着没有记录 - 就像这样:
仅供参考,如果第一个记录为空,
int.Parse
将抛出异常 - 这与零行不同。也许您应该检查 null 值,或使用int.TryParse
代替。reader.Read()
advances the reader to the next record, where the reader is initially set to before the first record. If callingreader.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 ifreader.Read()
returns false it means there were no records - like so: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 useint.TryParse
instead.检查 SqlReader 的 MSDN 文档 显示它有一个名为
HasRows
的属性,您可以使用它。Checking the the MSDN documentation for
SqlReader
reveals that is has a property calledHasRows
which you can use.Read() 获取结果集的下一行。
因此,如果您返回一行,则第一次读取会获取该行,而第二次 Read() 返回 false,因为没有第二行 - 所以会发生其他情况。
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.