4

ResultSet videoFilenames 应该有 4162 行(我在数据库中测试了查询),但是 while 循环“while (videoFilenames.next())”只迭代一次 - 在 ResultSet 中的第一个文件名之后,while 循环刚刚结束!谁能帮我弄清楚为什么?

/*
 * Run: java -cp .:ojdbc6.jar FindVideosWithoutTranscodes
 */

import java.io.*;
import java.sql.*;

public class FindVideosWithoutTranscodes {

    public static void main(String[] args) throws Exception {
        //connect to database
        Class.forName("oracle.jdbc.OracleDriver");
        String serverName = "***.***.***.***";
        String portNumber = "****";
        String sid = "*****";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String username = "*****";
        String password = "*****";
        Connection conn = DriverManager.getConnection(url, username, password);
        Statement stmt = conn.createStatement();

        //create output file
        BufferedWriter out = new BufferedWriter(new FileWriter("mp2_files_without_transcodes.txt"));

        //get ResultSet of mp2 filenames
        ResultSet videoFilenames = stmt.executeQuery("select filename from archivefile where filename like '%.mp2'");

        System.out.println("Making list of mp2 files without transcodes...");

        //for each mp2 file
        String filename;
        ResultSet smallTranscode;
        ResultSet largeTranscode;
        while (videoFilenames.next()) {
            filename = videoFilenames.getString(1);

            //check for -700.mov file
            System.out.println(filename.substring(0, filename.length() - 4) + "-700.mov"); //test
            smallTranscode = stmt.executeQuery("select * from archivefile where filename='" + filename.substring(0, filename.length() - 4) + "-700.mov'");
            if (!smallTranscode.next())
                out.write(filename + "\n");
            else {
                //check for -6500.mov file
                System.out.println(filename.substring(0, filename.length() - 4) + "-6500.mov"); //test
                largeTranscode = stmt.executeQuery("select * from archivefile where filename='" + filename.substring(0, filename.length() - 4) + "-6500.mov'");
                if (!largeTranscode.next())
                    out.write(filename + "\n");
                largeTranscode.close();
            }
            smallTranscode.close();
        }

        System.out.println("Done.");

        out.close();
        videoFilenames.close();

    }

}
4

2 回答 2

4

每个 Statement 对象只能同时打开一个 ResultSet 对象

http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html

因此,一旦使用相同的 Statement 实例在 while 循环中执行第二个查询,您将关闭 videoFilenames ResultSet。

于 2012-09-04T19:28:35.287 回答
2

Java 声明文档说;

默认情况下,每个 Statement 对象只能同时打开一个 ResultSet 对象。因此,如果一个 ResultSet 对象的读取与另一个 ResultSet 对象的读取交错,则每个对象都必须由不同的 Statement 对象生成。Statement 接口中的所有执行方法都会隐式关闭语句的当前 ResultSet 对象(如果存在打开的对象)。

换句话说,您不能循环遍历一个 ResultSet 并使用相同的stmt对象创建另一个,这将关闭第一个 ResultSet 并结束循环。

于 2012-09-04T19:28:02.277 回答