如何检查数据读取器是否为空?
我有一个 aspx 页面,允许用户将修改后的条目提交到数据库中,但是当用户单击 Submit
来触发存储过程时,我想首先运行检查以查看修改后的行是否带有存在同样的关系。
我将以下查询的结果传递
SELECT SwitchRoom.ModifiedID FROM SwitchRoom WHERE
SwitchRoomID = @ChkSwitchRmID", constring;
到 DataReader 中以确定该关系是否存在。
我需要它来确定读取器是否返回 NULL 以允许过程执行,如果不返回,则不允许用户保存信息。
我已经尝试过以下操作:
if (dbreader = NULL)
{
Fire Procedure
}
else
{
"Error Message"
}
我什至尝试将读取器传递到数据表中并针对该数据表运行它,但没有任何运气。
如何检查 DataReader 的结果是否为 null
?
I have an aspx page which allows a user to submit modified entries into the database, but when the user clicks Submit
to fire the stored procedure I want to first run a check to see if a modified row with the same relationship exists.
I am passing the results of the following query:
SELECT SwitchRoom.ModifiedID FROM SwitchRoom WHERE
SwitchRoomID = @ChkSwitchRmID", constring;
into a DataReader
to determine if that relationship exists.
I need it to determine whether the reader returns NULL
to allow the procedure to execute, if it doesn't, then don't allow the user to save the information.
I've tried the following:
if (dbreader = NULL)
{
Fire Procedure
}
else
{
"Error Message"
}
and I've even tried passing the reader into a datatable
and running it against that without any luck.
How do I check the restults of a DataReader for null
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我更喜欢将 ExecuteScalar 与对匹配行进行计数的查询一起使用:
然后将 Execute scalar 的结果与零进行比较。不需要空检查。
如果您确实想使用 reader 方法,您可以使用以下属性来检查它是否有任何行。即使该对象不返回任何内容,也不会为 null。
I prefer using ExecuteScalar with a query that counts the matching rows:
Then compare the result of Execute scalar to zero. No null check required.
If you really want to use the reader method you can use the following property to check if it has any rows. The object will not be null even if it returns nothing.
尝试 if (!dbReader.Read() || dbreader.IsDbNull(field)} { .. }
Try
if (!dbReader.Read() || dbreader.IsDbNull(field)} { .. }
Reader 不会返回 null 对象,要查明 Reader 是否返回任何行,您可以使用 if(dbreader.Read())
The Reader will not return a null object, To find out if the reader returned any rows you can use
if(dbreader.Read())
您正在寻找 DBNull 类型。数据库不发送实际的空引用,它们发送 C# 中的特殊数据类型来表示数据库 NULL 值。
You're looking for the DBNull type. Databases don't send actual null-references, they send a special datatype in C# to represent a database NULL value.
基本上,您想知道是否
返回任何记录?
读者永远不会是空的。相反,您需要检查读取器是否不包含要读取的记录。
So basically, you want to know if
returns any records?
The reader would never, ever be null. You instead need to check that the reader contains no records to read.