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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With