日期:2014-05-17  浏览次数:20795 次

java代码向数据库插入数据报错
当我写了一段简单的插入程序 向orcale中插入数据,当数据量小的时候没有问题,当超过5000条的时候就会报数据库连接出错,导致有些数据插入出现问题。

------解决方案--------------------
用excuteBatch。简单的例子:

Java code

String s = "";
        File f = new File(fileName);
        if (!f.exists()) {
            throw new Exception("file doesn't exist....");
        }
        BufferedReader br = null;
        PreparedStatement pstmt = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(f)));
            String sql = "insert into tbl_report(a,b,c,d)"
                    + "values(?,?,?,'2009-12-07')";
            pstmt = con.prepareStatement(sql);
            // 循环外部准备好prepareStatement;
            while ((s = br.readLine()) != null) {
                if (s.indexOf("合计") > 0) {
                    continue;
                }
                String[] c = s.split("\t");
                printArray(c);
                if (c.length == 3) {
                    // 加入批量参数
                    pstmt.setString(1, c[0]);
                    pstmt.setString(2, c[1]);
                    pstmt.setString(3, c[2]);
                    pstmt.addBatch();
                }
            }
            // 一次执行。
            pstmt.executeBatch();
            System.out.println("file write back finished");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }