简体   繁体   中英

What is causing Java program to treat the two ResultSet.getString() methods differently?

If "FirstName" and index 1 refer to the same column in a query, and rs is a ResultSet , why would

if(rs.getString("FirstName")!=null) fullName = rs.getString("FirstName");

and

if(rs.getString(1)!=null) fullName = rs.getString(1);

behave differently?

According to the Java docs, using either the columnIndex or the columnLabel both return the value of the designated column.

I'm running into a weird problem when I use the columnIndex instead of the columnLabel , for some reason, after the jsp has been running for a few hours/days then if(rs.getString(1)!=null) evaluates to true even when the String is null . When I use the columnLabel instead, the problem doesn't happen. Can anyone tell me why this might be happening?

Extra background info

The program runs in Tomcat. We updated Tomcat, the JVM, and our database driver on the same day, and this started happening. If we reload the app in Tomcat, it starts working correctly, at least for a few hours. We switched back to the old database driver and the problem continues, so we have ruled out the database driver.

rs.getString(1)返回在执行您的SQL查询的第一列中的数据(由preparedStatement ),它不需要的FirstName ,则需要交叉检查,在您的SQL查询preparedStatement如下:

SELECT FirstName from X;//you might add where conditions

From your comment:

it just starts returning the String "null" instead of the actual null value. So the fullName becomes the String "null".

In other words the problem is different from what is stated in your question. null and "null" aren't the same thing, so there is no reason for rs.getString(1) == null to return true if the actual value is "null" .

I would say you probably have "null" in your database somewhere. Check. Or else you are using String.valueOf(null) somewhere in your code, possibly indirectly, eg via println(null) , which calls it, so the output is "null" .

We have solved it. We decided to try a different SQL driver (we were using a Microsoft driver before, we switched to JTDS) and all problems have gone away.

So I'm guessing the Microsoft driver was returning the string "null" when it should have been returning null .

So to answer the question, the ResultSet.getString() method was probably behaving correctly all along, but the SQL driver was returning bad data.

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