0

在过去的 2 个小时里,我一直在试图找出结果集出了什么问题。我正在尝试连接到 MS Access 数据库,并且我有一个类似的工作方法,除了 sql 语句不同外,几乎完全相同。由于 sql 语句突出显示了表中的所有内容,因此我认为结果集会起作用,但显然不是。谁能给我指点?

这是我的代码:

    public static Video[] searchdatabase(String videoname, String uploadername, int likes, int dislikes, int favorites, int subscribers,int views, String category) throws SQLException
{
    String sql = "SELECT COUNT(VideoID) AS Num FROM tblYoutubeVideo";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);

rs.next();

int numrows = rs.getInt("Num");
    System.out.println("Numrows: "+numrows);
Video[] arr2 = new Video[numrows];

    sql = ("SELECT * FROM tblVideo, tblUploader WHERE tblVideo.Video_Name LIKE '"+videoname+"' AND tblUploader.Uploader_Name LIKE '"+uploadername+"'AND tblVideo.Views>"+views+" AND tblVideo.Likes>"+likes+" AND tblVideo.Dislikes<"+dislikes+" AND tblVideo.Favorites>"+favorites+" AND tblUploader.Subscribers>"+subscribers+"ORDER BY (Likes+(Views*0.5)+(Favorites*2)+(Subscribers*2))-2");
System.out.println(sql);
    stmt = conn.createStatement();
rs = stmt.executeQuery(sql);


    for (int i=0;i<arr2.length;i++)
    {
        rs.next();
        int uploaderid2 = rs.getInt("UploaderID");
        String uploader_name2 = rs.getString("Uploader_name");
        int subscribers2 = rs.getInt("Subscribers");
        int videoid2 = rs.getInt("VideoID");
        String video_name2 = rs.getString("Video_name");
        int favorites2 = rs.getInt("Favorites");
        String category2 = rs.getString("Category");
        int views2 = rs.getInt("Views");
        int likes2 = rs.getInt("Likes");
        int dislikes2 = rs.getInt("Dislikes");

        Video temp = new Video(uploaderid2, uploader_name2, subscribers2, videoid2, video_name2, favorites2, category2, views2, likes2, dislikes2);

        System.out.println(arr2[i]);
        arr2[i] = temp;
    }


    return arr2;

}

提前致谢 :)

4

1 回答 1

0

我怀疑问题出在这里:

rs.next();

你忽略了 的返回值next(),它告诉你是否真的移动到另一个有效行,或者你是否已经到达结果的末尾。您当前假设您有numrows结果,即使numrows是行数tblYoutubeVideo并且您的实际查询已被过滤。

我个人会完全删除第一个查询 - 只需使用 anArrayList<Video>代替,而不是你的for循环,有:

List<Video> videos = new ArrayList<Video>();
while (rs.next())
{
    ... read data ...
    videos.add(new Video(...));
}

此外,并不是说您当前的代码容易受到SQL 注入攻击。与其直接在 SQL 中包含值,不如将参数化 SQL 与PreparedStatement. 您在 SQL 本身中指定占位符,并在语句中设置参数值。

此外,您应该以finally块的形式关闭语句和结果集。(我个人也会关闭连接 - 使用连接池,以便您始终可以打开连接、使用它并关闭它。)

于 2013-04-29T18:22:39.307 回答