I am writing a Java class to insert data to a database with an iteration. Although I can now insert data, I am struggling in handling Oracle errors. In this case, I have deliberately created a Primary Key Constrain error by trying to insert duplicate primary keys (I have pre-loaded the database with the same entries as I am trying to insert with Java)
So as expected, I get the "ORA-00001: unique constraint". However, the problem I am having, is that after 300 iterations, I reach a new error:"ORA-01000: maximum open cursors exceeded"
I guess the issue is that every failed executeUpdate()
keeps a cursor open.
I have temporarily solved the issue by including a close()
statement on the catch of the error. However, I am wondering:
- Should the failed
executeUpdate()
not be closing the cursor? - Is there a better way I can close cursors on Exception?
- Why does it return a null Exception?
My Java Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestOracleError {
private static Connection conn;
public static void main(String[] args) {
//Connect
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:"+
"@XXX.XXX.XXX.XXX:1521:XXXX", "XXXX", "XXXX");
}
catch(SQLException e) {
System.err.println(e.getMessage());
}
//Iterate insert
for(int i=1; i<5000; i++){
PreparedStatement pstmt=null;
try {
//Deliberate error on the SQL (Primary Key Constraint)
pstmt = conn.prepareStatement("INSERT INTO DUMMY (ID) VALUES "
+"('"+i+"')");
pstmt.executeUpdate();
pstmt.close();
}
catch(Exception e) {
System.err.println("DB Error on iteration "+i+": " +
e.getMessage());
//If I add the following line then I can close the error!
//try {pstmt.close();} catch (Exception e1) {}
}
}
}
}