Unable to resolve error - java.sql.SQLException: O

2019-08-18 06:39发布

问题:

I made a java method to add a row to a database. I am calling this method about 1000 plus times for testing purposes. I called the close() method on my prepared statement and i am still getting the oracle error whenever this method is called to insert a row.

Error

ORA-01000: maximum open cursors exceeded

Source Code

public void insertARow(ArrayList<String> row)
{
    try
    {
        //Proper SQL statement here, checked by running on DB  
        String insert = "INSERT INTO user.info(cola,colb) values(?,?)";

        //Add a row 
        PreparedStatement ps = con.prepareStatement(insert);//con is a connection object 
        //'row' is an arraylist of strings
        for(int i = 0; i < row.size(); i++ )
        {

            int j = 1 +  i ; 
            String temp = row.get(i);
            ps.setString(j , temp);
        }

        ps.executeUpdate();//The reason for problems !!!
        ps.close();

    }catch(SQLException e)
    {
        System.out.println("Cannot add row !");
        e.printStackTrace();
    }
}

回答1:

If you're trying to perform the same operation a 1000 times, I would advise re-using the same PreparedStatement or using addBatch() and executeBatch() combo.

If you're planning to re-use your PreparedStatement, here's something that you can do:

public void insertARow(PreparedStatement ps, ArrayList<String> row){
 //your code
}

public void calledMethod(){
 String insert = "INSERT INTO user.info(cola,colb) values(?,?)";
 PreparedStatement ps = null;

 try{
   ps = con.prepareStatement(insert);
   /**
    * Here you make the call to insertARow passing it the preparedstatement that you
    * have created. This in your case will be called multiple times.
    */
   insertARow(ps, row);
 }finally{
   if(ps != null){
     //close ps
   }
 }
}