2

我正在使用 JDBC 和 SQLite 在同一个 .java 文件中对 2 个单独的数据库运行查询,但是当我尝试对单独的结果集进行第二次调用时,我收到一个错误,即结果集已关闭。我设置了连接和所有内容,然后进行了 3 次单独的调用,就像这样......然后调用ResultSet对象以获取数据。我在第一次调用时遇到错误mealSet

        Class.forName("org.sqlite.JDBC");
        Connection conn1 = null;
        conn1 = DriverManager.getConnection("jdbc:sqlite:workoutLog.db");
        @SuppressWarnings("null")
        PreparedStatement workoutQuery= conn1.prepareStatement("SELECT * FROM workoutLog");// ORDER BY t desc limit 1");
        ResultSet workoutSet = workoutQuery.executeQuery();


        Class.forName("org.sqlite.JDBC");
        Connection conn2 = null;
        conn2 = DriverManager.getConnection("jdbc:sqlite:foodLog.db");
        PreparedStatement getFoodLog = conn2.prepareStatement("SELECT * FROM foodLog");// ORDER BY t desc limit 3");
        ResultSet mealSet = getFoodLog.executeQuery();
        mealSet.next();

        meals.add(breakfast);
        meals.add(lunch);
        meals.add(dinner);

        weekStart = workoutSet.getInt(ID_COLUMN);
        weekEnd = weekEnd + 6;
        Class.forName("org.sqlite.JDBC");
        Connection conn3 = null;
        conn3 = DriverManager.getConnection("jdbc:sqlite:projectLog.db");
        PreparedStatement getProjectLog = conn3.prepareStatement("SELECT * FROM projectLog");
        ResultSet projectSet = getProjectLog.executeQuery();
        ResultSetMetaData meta = projectSet.getMetaData();


        for (int i=3;i<meta.getColumnCount()-1;i++){
            String prj="";
            projects.add(prj);
        }


        while ( projectSet.next()){

            for (int i=3;i<=meta.getColumnCount()-1;i++){
                int arrayPos = 0;
                String temp =projectSet.getString(i) + "\n";
                projects.set(arrayPos, projects.get(arrayPos).concat(temp));
                projectNames.add(meta.getColumnName(i));
                totalHours+=projectSet.getInt(3);
                totalMinutes+=projectSet.getInt(meta.getColumnCount());
                arrayPos++;
            }


            for (int k=0;k<=2;k++){
            breakfast=mealSet.getString(BREAKFAST_COLUMN)+" \n";
            lunch=mealSet.getString(LUNCH_COLUMN)+" \n"; 
            dinner=mealSet.getString(DINNER_COLUMN)+" \n";
            meals.set(0, meals.get(0).concat(breakfast));
            meals.set(1, meals.get(1).concat(lunch));
            meals.set(2, meals.get(2).concat(dinner));
            mealSet.next(); 
        }

错误是...

Exception in thread "main" java.sql.SQLException: ResultSet closed
    at org.sqlite.RS.checkOpen(RS.java:63)
    at org.sqlite.RS.markCol(RS.java:77)
    at org.sqlite.RS.getString(RS.java:313)
    at WeeklyReport.main(WeeklyReport.java:99)
4

1 回答 1

1

您不能ResultSet为大量查询重复使用同一个实例。一个ResultSet实例只能用于获取一个查询的结果。

此外,正如ResultSet JavaDoc 中所写:

ResultSetStatement当生成它的对象关闭、重新执行或用于从多个结果序列中检索下一个结果时,对象会自动关闭。

于 2013-05-12T20:55:32.080 回答