When to call getWarnings () in joins, statements, and ResultSets with JDBC?

In JDBC, the Connection , Statement and ResultSet types have a getWarnings() method, which is specified to generate the first warning associated with objects of this type. The second and subsequent warnings, if they exist, are tied to the first warning (if it even exists, null is generated if there are no warnings).

The specifications say that warnings associated with objects of these types are cleared after certain actions. For example, warnings in a ResultSet are cleared when each new line is read.

The SQLWarning type is a subtype of SQLException . So will the presence of a warning indicate an exception? And will this exception be bound to the related object if the type of exception environment is SQLWarning ?

What interests me, and it could be a specific driver, as I know, when should I call getWarnings() and expect a non- null response? To deliver in another way is a warning that is present on the JDBC object and is accessible using getWarnings() only after this object raised an exception? (and is this exception a warning?)

Should I call getWarnings() to look for warnings after each JDBC "just to be sure" operation, if my goal is to keep track of every warning?

+6
source share
3 answers

On the other hand, you should explicitly check for any SQL warnings because they are not propagated through standard exception handling mechanisms. To do this, call the appropriate getWarnings method on the corresponding JDBC object.

[link]

Honestly, I never found myself checking warnings. Maybe I never did serious things.

+4
source

SQLWarning objects are a subclass of SQLException that deal with database access warnings.

Warnings do not stop application execution, as exceptions do; they simply warn the user that something is not going as planned.

You can report a warning about a Connection object, a Statement object (including PreparedStatement and CallableStatement ), or a ResultSet .

Each of these classes has a getWarnings method, which you must call to see the first warning reported on the caller:

 SQLWarning warning = stmt.getWarnings(); if (warning != null) { System.out.println(\"n---Warning---n\"); while (warning != null) { System.out.println(\"Message: \" + warning.getMessage()); System.out.println(\"SQLState: \" + warning.getSQLState()); System.out.print(\"Vendor error code: \"); System.out.println(warning.getErrorCode()); System.out.println(\"\"); warning = warning.getNextWarning(); } } 
+7
source

Yes, you need to explicitly receive alerts if you really want to watch every alert. But why do you have to do this?

As an alternative to Spring, JdbcTemplate gives you the option to log warnings or throw SQLWarningException when warnings occur. The default behavior is to log warnings because, well, they are warnings. I hope this is enough for your purposes.

+3
source

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


All Articles