不确定如何修复无效的游标状态

时间:2013-04-29 18:14:17

标签: java sql database

我一直试图找出过去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;

}

提前致谢:)

1 个答案:

答案 0 :(得分:0)

我怀疑问题在这里:

rs.next();

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

我会亲自删除第一个查询 - 只需使用ArrayList<Video>代替for循环,而不是:{/ p>

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

此外,并非您当前的代码容易受到SQL injection attacks的攻击。您应该将参数化SQL与PreparedStatement一起使用,而不是直接在SQL中包含值。您可以在SQL本身中指定占位符,并在语句中设置参数值。

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