tags:

views:

316

answers:

3

I'm formatting a ResultSet to output to a CSV file. As such I really don't care about the Java types of the result set, beyond maybe knowing if it's text or numbers.

Does JDBC guarantee getString will always give a string representation of the values,atleast for single values (I don't need to concern myself about java.sql.Types.ARRAY,java.sql.Types.JAVA_OBJECT and a few others).

e.g. given resultSetMetaData.getColumnType(i) is a Types.FLOAT or a Types.BIGDECIMAL. will rs.GetString(i) always yield some String ?

i.e. Are there cases getString will throw an SQLException or return null when a getXXX would give me the value ?

A: 

The documentation does seem to be ambiguous, but I would not expect it to attempt conversion.

Instead, use String.valueOf(getObject()) (with appropriate checks for null and objects such as arrays that don't have a simple string representation).

kdgregory
+2  A: 

java.lang.String is a final class - it cannot, ever, have a subclass. So any method that returns String will either return an instance of the class java.lang.String, or a null, or throw an exception.

As for conversion, it is up to the JDBC driver if it will allow you to convert from non-String types. I suspect many will have an issue with it.

I would suggest that you do this instead:

Object item = resultSet.getObject(i);
String strValue = (item == null ? null : item.toString());

That should be more robust, since getObject() will always do the sensible thing.

skaffman
Or throw `SQLException`
kdgregory
And that is the question, are there cases getString will throw an SQLException or return null when a getXXX would give me the value ?
Anonym
A: 

Yup, check this : http://java.sun.com/docs/books/tutorial/jdbc/basics/retrieving.html

JDBC allows a lot of latitude as far as which getXXX methods you can use to retrieve the different SQL types. For example, the method getInt can be used to retrieve any of the numeric or character types. The data it retrieves will be converted to an int; that is, if the SQL type is VARCHAR , JDBC will attempt to parse an integer out of the VARCHAR. The method getInt is recommended for retrieving only SQL INTEGER types, however, and it cannot be used for the SQL types BINARY, VARBINARY, LONGVARBINARY, DATE , TIME, or TIMESTAMP.

But be careful, different JDBC driver may yield different result.

nanda