When to call getWarnings() on Connections, Statements, and ResultSets with JDBC?
In JDBC the Connection
, Statement
, and ResultSet
types each have a getWarnings()
method that is specified to produce the first warning associated with objects of that type. The second and subsequent warnings, if they exist, are chained onto the first warning (if it even exists, null
is produced if there are no warnings).
The specs say that warnings associated with objects of these types are cleared after certain actions. For example warnings on a ResultSet
are cleared when each new row is read.
The SQLWarning
type is a subtype of SQLException
. So w开发者_JAVA技巧ould the presence of a warning be indicated by an exception? And that exception would be chained to the associated object if the exception's runtime type is SQLWarning
?
What I'm wondering is this, and it might be driver specific, how do I know when I should call getWarnings()
and expect a non-null
response? Put another way, is a warning present on a JDBC object and available with getWarnings()
only after that object has thrown an exception? (and that exception is the warning?)
Should I call getWarnings()
to look for warnings after every JDBC operation "just to be sure" if my goal is to observe every warning?
SQLWarning
objects are a subclass of SQLException
that deal with database access warnings.
Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned.
A warning can be reported on a Connection
object, a Statement
object (including PreparedStatement
and CallableStatement
objects), or a ResultSet
object.
Each of these classes has a getWarnings
method, which you must invoke in order to see the first warning reported on the calling object:
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();
}
}
On the other hand, you must explicitly check for any SQL warnings, because they aren't propagated via the standard exception-handling mechanisms. To do so, call the appropriate getWarnings method on the relevant JDBC object.
[reference]
Frankly speaking, I have never found myself checking for warnings ever. May be I have never done any serious stuff.
Yes, you'd need to getWarnings explicitly if you really want to observe every warning. But why would you want to do such a thing?
Alternatively Spring's JdbcTemplate gives you the option of logging warnings or throwing SQLWarningException when there are warnings. The default behavior is to log warnings because, well, they're warnings. Hopefully this is sufficient for your purposes, too.
精彩评论