*
The moose likes JDBC and the fly likes can this be solved Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "can this be solved" Watch "can this be solved" New topic
Author

can this be solved

ben riches
Ranch Hand

Joined: Nov 08, 2002
Posts: 126
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:

Thanks
Ben
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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!


[Jess in Action][AskingGoodQuestions]
Chris Dillon
Greenhorn

Joined: Feb 13, 2004
Posts: 6
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
Chris Dillon
Greenhorn

Joined: Feb 13, 2004
Posts: 6
yahoo! Sync posting! ;D
ben riches
Ranch Hand

Joined: Nov 08, 2002
Posts: 126
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: can this be solved