Database Transactions with JDBC
When a connection is created using JDBC, by default it is in auto-commit mode. This means that each SQL statement is treated as a transaction and will be automatically committed immediately after it is executed.The following code illustrates this:
Code:
conn.setAutoCommit(false);
try{
PreparedStatement updateSales = _
conn.prepareStatement(
"UPDATE PRODUCT_SALES SET NUMBER_OF_SALES=NUMBER _
_OF_SALES+1 WHERE
PRODUCT_ID = ?");
updateSales.setString(1, productId);
updateSales.executeUpdate();
PreparedStatement updateInventory = _
conn.prepareStatement(
"UPDATE INVENTORY SET STOCK=STOCK-1 _
WHERE PRODUCT_ID = ?");
updateInventory.setString(1, productId);
updateInventory.executeUpdate();
conn.commit();
}
catch(SQLException se){
conn.rollback();
}
conn.setAutoCommit(true);
Bookmarks