Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird
Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird
Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
PreparedStatement updateSales = null;<br />
String updateString = "update COFFEES " +<br />
"set SALES = ? where COF_NAME like ?";<br />
updateSales = con.prepareStatement(updateString);<br />
try {<br />
int [] salesForWeek = {175, 150, 60, 155, 90};<br />
String [] coffees = {"Colombian", "French_Roast",<br />
"Espresso", "Colombian_Decaf",<br />
"French_Roast_Decaf"};<br />
int len = coffees.length;<br />
for(int i = 0; i < len; i++) {<br />
}<br />
updateSales.setInt(1, salesForWeek[i]);<br />
updateSales.setString(2, coffees[i]);<br />
try {<br />
updateSales.executeUpdate();<br />
} catch(SQLException ex) {<br />
}<br />
} finally {<br />
}<br />
if (ex.getErrorCode() == ...)<br />
// do something<br />
else<br />
throw new BusinessDBException(ex);<br />
updateSales.close();<br />
Illustration 3.1.: Typical resource allocation and error handling patterns<br />
The nested try/catch block shows you an example of handling a deadlock error if<br />
it happens (first scenario according to our classification), otherwise the exception<br />
is converted and passed to the upper layers (second scenario). As you see, there is<br />
no special treatment to the third scenario.<br />
A possible bug in the <strong>JDBC</strong> <strong>driver</strong> could have generated runtime exception in the<br />
PreparedStatement.executeUpdate() method, which would lead to the<br />
statement handle leakage if no try/finally block is used to do the resource cleanup.<br />
As a rule of thumb, the “try” keyword should go right after the resource was<br />
allocated and the “finally” keyword should be placed right before the resource is<br />
freed.<br />
Such coding practice might look weird, because on the first sight the whole<br />
purpose of using the PreparedStatement is neglected – statement is prepared,<br />
used only once and then deallocated. However, when this practice is combined<br />
with the connection and statement pooling, it brings enormous advantage to the<br />
application code. The code becomes much more manageable – resource<br />
allocations and deallocations happen in the same method and software developer<br />
must not remember the places where the same prepared statement might be used –<br />
statement pool will either reuse the statement or it will prepare a new one, if it<br />
detects that all pooled prepared statements are currently in use. As a side effect,<br />
Chapter 3. Handling exceptions 25