简体   繁体   中英

Error when checking if SqlDataReader column has null value

One of the guys working on a project with me keeps getting an error when the code trys to validate if SqlDataReader returns a null value in a column. He runs this code:

if (!DB_Conn.isConnected()) DB_Conn.Connect();
using (SqlDataReader dr = DB_Conn.QueryDB(query))
{
   if (dr.HasRows && !dr.IsDBNull(0))
   {
       maxID = dr.GetInt32(0);
   }
}

But gets an error that Its an invalid attemtp to read when no data is present at the !dr.IsDBNull(0) command.

If i run this same code but i query a different table, it works.

Also, i run both queries and they return the expected null value. The querys are:

SELECT MAX(ID) FROM Loan;
SELECT MAX(ID) FROM InternationalSwap;

I dont think the querys have any affect on the reason why we are getting this error at one machine and not the other.

You need to call the Read method before trying to access any columns:

while (dr.Read())
{
    if (!dr.IsDBNull(0))
        maxID = dr.GetInt32(0);
}

But... if you only need a single value then you should probably use something like ExecuteScalar rather than a datareader.

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