how to handle exceptions in the while loop?
I have a situation in java where in:
while(resultset.next()){
try{
//some executable prepared statements written
}
catch(MySQLIntegrityConstraintViolationException ex){
//block2
}
catch(SQLException ex){
//block1
}
}
now here , what I am trying to do is that if an MySQLIntegrityConstraintViolationException
is seen, I have to skip it and just continue with the next record...
I am unable to find a mechanism to do this.
Please could someone suggest what should be done so that the exception is ignored.
Please let me know..Thank you开发者_开发百科 very much in advance.
Understand your database better.
There are lots of issues here.
1) does your prepared statement participate in a transaction? (i.e. does it rollback?)
2) does the prepared statement update rows?
3) can you guarantee that the database is in a known state after the exception is caught and handled?
Trying to ignore the exception is the wrong approach. The current code (as shown) does let you repeat the prepared statement after the exception is caught. 'MySQLIntegrityConstraintViolationException
' tells me that the database could not do something you asked it to; maybe a duplicate key or a delete involving a required foreign key.
You need to understand the constraints of the database tables to really know how to should respond to this exception.
In the case of inserting duplicates, I've had situations where I had to tell the db engine to ignore dups, or to indicate a table/file dups should be piped to.
The best answer here is to understand why your prepared statement is throwing the exception and then plan how to respond to the situation. If you already know this, please add it to the question, otherwise we'll be grabbing at straws.
I think you might be getting any other exception , try doing following to find out if you are getting any other exception,
while(resultset.next()){
try{
//some executable prepared statements written
}
catch(Exception ex){
if(ex instanceof MySQLIntegrityConstraintViolationException)
continue;
else
ex.printStackTrace();
}
}
精彩评论