I made a java application that read a text file and store it in a database.The database has 2 tables So in order to store the value of text i created two prepared statement in this order
- code for storing data in table 1
- code for storing data in table 2
And that worked perfectly. However, when there is a Semantic Errors in the second table , the data in the first are still stored , which is not what i intended to.
In a nut shell , if there any semantic error int the second table i want nothing to be stored in the database. So how can i do it ?
-
3You need to think atomically, or transactionally :-)Kerrek SB– Kerrek SB2011年08月16日 21:34:18 +00:00Commented Aug 16, 2011 at 21:34
-
download.oracle.com/javase/tutorial/jdbc/basics/…Vlad– Vlad2011年08月16日 21:35:56 +00:00Commented Aug 16, 2011 at 21:35
-
i tried to empty the stored line back in the code for the second table but it won't work. I didn't understand your answerLou– Lou2011年08月16日 21:36:59 +00:00Commented Aug 16, 2011 at 21:36
4 Answers 4
It may depend on your database, but you should use a transaction, catch any exceptions and rollback the transaction in the case where the data is bad.
Comments
What you want is a transaction in your database, which will allow you to roll back the first insert if something goes wrong with the second one.
You're not specifying which database connection technology you're using, but whichever it is try looking through its documentation for "transaction" support.
Comments
You need to use a transaction. Set autocommit on the connection to false, execute the 2 statements. If there is an exception then catch this and rollback the transaction, otherwise commit. Thanks
Comments
Verify the inputs before writing them to the database.