Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JDBC SQLExceptions for DB2 more descriptive?

How to make SQLExceptions thrown by DB2 JDBC driver more descriptive?

Currently I am getting this kind of exceptions. It is cumbersome to work with these cryptic SQLCODE and SQLSTATE numeric values. Is there a way where to make the SQL exception to contain code description.

Caused by: com.ibm.db2.jcc.b.SqlException: DB2 SQL error: SQLCODE: -302, 
     SQLSTATE: 22001, SQLERRMC: null
      at com.ibm.db2.jcc.b.hh.c(hh.java:1662)
      at com.ibm.db2.jcc.b.hh.a(hh.java:1238)
      at com.ibm.db2.jcc.c.db.n(db.java:737) 
      ....

e.g. SQLSTATE 22001 has this description:

Character data, right truncation occurred; for example, an update or insert value is a string that is too long for the column, or a datetime value cannot be assigned to a host variable, because it is too small.

Edit: I am also using Spring and Hibernate frameworks.

like image 561
Juha Syrjälä Avatar asked Sep 24 '09 09:09

Juha Syrjälä


People also ask

When JDBC encounters an error during an interaction with a data source it throws an instance of?

Overview of SQLException When JDBC encounters an error during an interaction with a data source, it throws an instance of SQLException as opposed to Exception . (A data source in this context represents the database to which a Connection object is connected.)

What are the exceptions in JDBC?

JDBC-related exception mostly throws SQLException, and it is a checked exception so we must either catch it or throw it. All the business logic and commit data should be done in a Try block, if any exception happened in the block we should catch and handle it in the Catch block.

Can we throw SQLException?

They didn't define public constructors in the SqlException class, because the SqlException class is meant to be thrown only by the classes that are clients to the Sql server directly (the most notable of these is SqlClient).

How to handle DB exception in Java?

SQLException Methods Gets the JDBC driver's error message for an error, handled by the driver or gets the Oracle error number and message for a database error. Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method.


1 Answers

Set the JDBC driver property retrieveMessagesFromServerOnGetMessage to true. Example connection url:

jdbc:db2://host:50128/MYDB:retrieveMessagesFromServerOnGetMessage=true;

See also DB2 11.1 Documentation

like image 78
andy Avatar answered Oct 08 '22 20:10

andy