This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes JDBC and the fly likes commit() and rollback() in a finally block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "commit() and rollback() in a finally block" Watch "commit() and rollback() in a finally block" New topic
Author

commit() and rollback() in a finally block

Jean Fore
Ranch Hand

Joined: Feb 23, 2006
Posts: 33
Hi, according to the Java coding conventions, isn't it appropriate to use the commit() or rollback() in a finally block? Please see the following code which is a portion of my program. Please let me know is it appropriate.

finally {
try {
if (dbConnection != null) {
if (errorFound) {
dbConnection.rollback();
} else {
dbConnection.commit();
}
dbConnection.close();
dbConnection = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}

Thanks
-JEAN
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60041
    
  65

Moved to the JDBC forum.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Mattias Arthursson
Ranch Hand

Joined: Jul 26, 2004
Posts: 90
In your code you risk leaving the connection hanging if any exception is encountered during commit() or rollback(). I'd probably put the rollback() in the catch block and the commit() last in the original try block, like so:


Admit nothing. Blame everyone. Be bitter.
Jean Fore
Ranch Hand

Joined: Feb 23, 2006
Posts: 33
Thank you so much for the response. Now I understand the flow of how to do this!
-JEAN
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: commit() and rollback() in a finally block
 
Similar Threads
.commit() and .rollback()
Transaction context propogation
JDBC-Auto commit
why my rollback doesn't work?
AutoCommit(False) and rollback bst practise