PostgreSQL resultSet.getLong () throws an ArrayIndexOutOfBoundsException when the column type is bigint

I have a view in PostgreSQL 9.1 with a bigint type column. This type should map to Long in Java, but it actually maps to BigInteger . So,

 resultSet.getLong(columnPos) 

throws an ArrayIndexOutOfBoundsException.

 resultSet.getBigInteger(columnPos) 

or

 resultSet.get(columnPos) 

with both the following toString and parsing. What will be the proper handling of this? Should I get BigInteger first, call toString and parse Long ? Or is there a better approach to tell ResultSet or ScrollableResults correct Java column type?

Thanks.

+4
source share
3 answers

The bigint data type bigint correctly to BigInteger , as it says: it is a large integer that may not fit into Long.

You can use resultSet.get(columnPos) and then check the class of the returned object.

We wrote a utility class for this, so we would do something like this:

 public Long getLongFromResultSet( ResultSet rs, int columnPos ) { Object value = rs.get( columnPos ); if( value instanceof Number) { //this should handle any numeric Java type like BigInteger, Long etc. return ((Number)value).longValue(); //autoboxing here } ... //handle non-Number cases } 
+1
source

Inserting a BigInteger value with jdbc

 BigInteger bi = new BigInteger("18446744073709551615"); // max unsigned 64-bit number statement.setObject(1, bi, Types.BIGINT); statement.execute(); 

when reading a result set: if facebok_id is of type BigInteger

 value.setFacebook_id(BigInteger.valueOf(rs.getLong("facebook_id"))); 
0
source

FWIW, in the current PostgreSQL JDBC implementation (pgjdbc) this does not seem to be a problem: getLong works fine in BIGINT columns. The current implementation does not even implement anything called getBigInteger. https://github.com/pgjdbc/pgjdbc/blob/master/pgjdbc/src/main/java/org/postgresql/jdbc/PgResultSet.java

In addition, getLong seems safe for SMALLINT, INT, and BIGINT.

0
source

Source: https://habr.com/ru/post/1381444/


All Articles