“ ResultSet位置不正确”调用了.next(),但仍然无法正常工作,请告知?

时间:2019-04-13 11:56:06

标签: java sql postgresql

我正在尝试从使用PostgreSQL创建的数据库中提取有关歌曲的数据。我一直收到此错误,我不知道该怎么办,因为我调用了resultSet.next()。 有什么建议吗?

     String SQL = "SELECT trackName, albumName FROM tracks, artists, 
     albums WHERE 'song' = tracks.trackname AND tracks.mainartist = 
     artists.artistname AND albums.artist = artists.artistname";

    try
    {
        org.postgresql.Driver.isRegistered();
        Class.forName("org.postgresql.Driver");
        Connection connection = DriverManager.getConnection(url,username,password); //creates a new connection

        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(SQL);
        resultSet.next();


        String album = resultSet.getString(3);
        String artist = resultSet.getString(4);
        String trackName = resultSet.getString(2);
        String feat = resultSet.getString(5);
        String date = resultSet.getString(6);

        console.println("");
        console.println("");
        console.println("Track Name: "+trackName);
        console.println("");
        console.println("Track Album: "+album);
        console.println("");
        console.println("Track Artist(s): "+artist);
        console.println("");
        console.println("Featuring: "+feat);
        console.println("");
        console.println("Track Release Date: "+date);
        console.println("");
        console.println("\n");

    }
    catch(Exception e)
    {
        console.println("SORRY, COULD NOT CONNECT YOU TO THE DATABASE.");
        console.println(e);
        console.println("");
        e.printStackTrace();
    }

我要在终端上打印出来

    SORRY, COULD NOT CONNECT YOU TO THE DATABASE.
    org.postgresql.util.PSQLException: ResultSet not positioned properly, 
    perhaps you need to call next.

这是stackTrace:

    org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
at org.postgresql.jdbc.PgResultSet.checkResultSet(PgResultSet.java:2772)
at org.postgresql.jdbc.PgResultSet.getString(PgResultSet.java:1894)
at Info.songInfo(Info.java:49)
at __SHELL14.run(__SHELL14.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at bluej.runtime.ExecServer$3.run(ExecServer.java:752)

1 个答案:

答案 0 :(得分:0)

由于您可能不在行中,因此在尝试从行中检索信息之前,应始终检查next的返回值。来自the JavaDoc

  

返回:true,如果新的当前行有效; false,如果没有更多行

我怀疑您的查询与任何行都不匹配,因此next返回false,但是您正试图从不存在的行中读取数据。

所以在您的情况下:

if (resultSet.next()) {
    String album = resultSet.getString(3);
    // ...
} else {
    // There were no matching rows
}