Error Handling and Clean Up
All
JDBC
method calls can throw
SQLException
or one of its subclasses if something
happens during a database call. Your code should be set up to catch
this exception, deal with it, and clean up any database resources
that have been allocated. Each of the JDBC classes mentioned so far
has a close( ) method associated with it.
Practically speaking, however, you only really need to make sure you
close things whose calling processes might remain open for a while.
In the examples we have seen so far, you only really need to close
your database connections. Closing the database connection closes any
statements and result sets associated with it automatically. If you
intend to leave a connection open for any period of time, however, it
is a good idea to close the statements you create using that
connection when you finish with them. In the JDBC examples you have
seen, this clean up happens in a
finally
clause. You do this
since you want to make sure to close the database connection no
matter what happens.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access