您的位置:首页 > 其它

ORA-01000:超出打开游标的最大数的原因和解决方案

2013-06-04 10:11 477 查看
原文发表于: http://www.laozizhu.com/view.jsp?articleId=34

先看有问题的代码 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class Test {

  public Connection getConnection() {

    String url = "jdbc:oracle:thin:@localhost:1521:ora9i";

    String user = "scott";

    String password = "tiger";

    Connection con = null;

    try {

      Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

      con = DriverManager.getConnection(url, user, password);

    } catch (Exception e) {

      e.printStackTrace();

    }

    return con;

  }

  public static void main(String[] args) throws SQLException {

    long a = 13819100000L;

    long b = 13819100600L; // 问题点

    Connection con = null;

    Statement stmt = null;

    Test insert = new Test();

    try {

      con = insert.getConnection();

      for (long c = a; c <= b; c++) {

        String sql = "insert into telepnum values(" + c + ")";

        stmt = con.createStatement(); // 这里是问题的所在

        stmt.executeUpdate(sql);

      }

      System.out.println("OK");

    } catch (Exception e) {

      e.printStackTrace();

    } finally {

      if (con != null) {

        con.close();

      }

    }

  }

}

分析 
在循环里面每次都 
stmt = con.createStatement(); 
而没有释放,这样每个都占用了一个服务器的游标资源,最后造成失败 

解决方案 
1 增加关闭语句 

      con = insert.getConnection();

      for (long c = a; c <= b; c++) {

        String sql = "insert into telepnum values(" + c + ")";

        stmt = con.createStatement(); // 这里是问题的所在

        stmt.executeUpdate(sql);

        stmt.close(); // 用完了就关闭好了

      }

3 改装成批量更新 

[Java] view
plaincopy

con = insert.getConnection();<br>      con.setAutoCommit(false);<br>      stmt = con.createStatement(); // 移动到这里,Statemet是可以重用的<br>      for (long c = a; c <= b; c++) {<br>        String sql = "insert into telepnum values(" + c + ")";<br>        stmt.addBatch(sql);<br>      }<br>      stmt.executeBatch();<br>      con.commit();  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐