oracle - Java Prepared Statement keeping cursor open after error -
i writing java class insert data database iteration. although can insert data, struggling in handling oracle errors. in case, have deliberately created primary key constrain error trying insert duplicate primary keys (i have pre-loaded database same entries trying insert java)
so expected, "ora-00001: unique constraint". however, problem having, after 300 iterations, reach new error:"ora-01000: maximum open cursors exceeded"
i guess issue every failed executeupdate()
keeps cursor open.
i have temporarily solved issue including close()
statement on catch of error. however, wondering:
- should failed
executeupdate()
not closing cursor? - is there better way can close cursors on exception?
- why return 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 sql (primary key constraint) pstmt = conn.preparestatement("insert dummy (id) values " +"('"+i+"')"); pstmt.executeupdate(); pstmt.close(); } catch(exception e) { system.err.println("db error on iteration "+i+": " + e.getmessage()); //if add following line can close error! //try {pstmt.close();} catch (exception e1) {} } } } }
if need insert many rows put creation of prepared statement outside loop , set values inside loop.
// moved outside preparedstatement pstmt=null; // using question mark placeholder variable pstmt = conn.preparestatement("insert dummy (id) values (?)"); (int = 1; < 5000; i++) { try { //deliberate error on sql (primary key constraint) // set variable in loop pstmt.setint(1, i); pstmt.executeupdate(); } catch (exception e) { system.err.println("db error on iteration "+i+": " + e.getmessage()); //if add following line can close error! //try {pstmt.close();} catch (exception e1) {} } } pstmt.close(); // moved out of loop
note: code don't close pstmt
if exception happens. statements remains opened. can potentially create problem of many open cursors.
generally best solution close resources in finally
block or use try resource statement
Comments
Post a Comment