2 messages in com.mysql.lists.javaWhy do Strings from ResultSet turns i...
FromSent OnAttachments
Barnet Wagman23 Dec 2003 07:31 
Barnet Wagman23 Dec 2003 07:39 
Subject:Why do Strings from ResultSet turns into nulls? (help!)
From:Barnet Wagman (bw@northbranchlogic.com)
Date:12/23/2003 07:31:53 AM
List:com.mysql.lists.java

After retreiving a String from a ResultSet, the String can be printed with println(), but attempting to copy it or store it in an ArrayList yields a null. I'm having this problem with MySQL version mysql-standard-4.0.13-pc-linux-i686 and mysql-connector-java-3.0.9-stable (and connector 3.0.8).

In the following code, KEYVAL is a VARCHAR(255). There is a unique index on KEYVAL.

The following works as expected:

PreparedStatement ps = con.prepareStatement("SELECT KEYVAL FROM A_TABLE"); ResultSet rs = ps.executeQuery(); rs.beforeFirst(); while ( rs.next() ) { String x = rs.getString(1); System.out.println(x); } ps.close(); rs.close();

However, if I try to put the Strings into an ArrayList, the ArrayList ends up containing nulls, except for the last element, i.e.

ArrayList A = new ArrayList(); PreparedStatement ps = con.prepareStatement("SELECT KEYVAL FROM A_TABLE"); ResultSet rs = ps.executeQuery(); rs.beforeFirst(); while ( rs.next() ) { String x = rs.getString(1); A.add(x); System.out.println(x + " " + A.get(A.size()-1)); } System.out.println(A.get(0) + " " + A.get(A.size()-1)); ps.close(); rs.close();

In the above code, the print statement in the loop works correctly, but after the loop the ArrayList contains nothing but nulls, EXCEPT for the last element, which contains the correct String.

Furthermore, if I try to copy the String in the loop, a NullPointerException is thrown:

PreparedStatement ps = con.prepareStatement("SELECT KEYVAL FROM A_TABLE"); ResultSet rs = ps.executeQuery(); rs.beforeFirst(); while ( rs.next() ) { String x = rs.getString(1); System.out.println(x); String y = new String(x); // A NullPointerException is thrown by the String constructor. } ps.close(); rs.close();

I've tried using getAsciiStream() to access the Strings; calling read() on the stream yields a NullPointerException.

Any thoughts about what might cause this and/or how to work around it would be appreciated. Could the problem be related to using VARCHAR(255)?

Thanks