Hello All, I have a big problem with my code. And I am not sure this can be solved. I have an sql statment, inside a loop so each loop though it will insert the right data to the database. Lets say the code is going to loop 4 times. The problem is I have an error in my sql statement on the last loop, the 3 previous loops will execute but the last loop will thow an exception. This is not what I want, I want the code to thow the exception first before any data is executed to the database if there is an exception, if not then execute the data. Here is my code that runs the sql statment:
I believe what you're after is the notion of a transaction. A transaction is basically a set of database operations that either all complete, or none complete. Partial transactions can be rolled back automatically, so that if a transaction fails in the middle, it's as if the transaction never happened, even if early parts of the transaction made changes (or appeared to have made changes) to the database. To use transactions with JDBC (given that your database supports them; most "real" databases do) you first call setAutoCommit(false) on the Connection object. Then you perform any number of queries. Then you either call commit() (if the transaction was successful) or rollback() (if it failed) on the Connection. You might then call setAutoCommit(true) to restore the default behavior, which is basically to call commit() automatically after every UPDATE or INSERT. Hope this helps!
Looks like dodgy code to me... Not sure I understood your code... Anyway, aren't you looking for some transaction? Open a transaction before your loop, roolback if there is an exception, and commit if there is not... Is that it? Cheers Chris
Joined: Feb 13, 2004
yahoo! Sync posting! ;D
Joined: Nov 08, 2002
Originally posted by Ernest Friedman-Hill:
Hope this helps!
Hello Ernest, Well first of all at least I know it is possible. But I am having trouble with where I should put each method in my code could you please help? Thanks Ben