简体   繁体   中英

How do I check a datareader for 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 ?

I prefer using ExecuteScalar with a query that counts the matching rows:

"SELECT count(*) FROM SwitchRoom WHERE SwitchRoomID = @ChkSwitchRmID"

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.HasRows) {....}

尝试if (!dbReader.Read() || dbreader.IsDbNull(field)} { .. }

Reader将不会返回空对象,要了解读者是否返回了任何行,可以使用if(dbreader.Read())

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

SELECT SwitchRoom.ModifiedID
FROM SwitchRoom
WHERE SwitchRoomID = @ChkSwitchRmID

returns any records?

The reader would never, ever be null. You instead need to check that the reader contains no records to read.

if  (!dbReader.Read())
{
    // execute procedure
}
else
{
    // error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM