Unable to get results from H2 db

2019-04-26 17:23发布

问题:

I'm trying to get values from h2 db, but always getting this error

 org.h2.jdbc.JdbcSQLException: No data is available [2000-171]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
    at org.h2.message.DbException.get(DbException.java:169)
    at org.h2.message.DbException.get(DbException.java:146)
    at org.h2.message.DbException.get(DbException.java:135)
    at org.h2.jdbc.JdbcResultSet.checkOnValidRow(JdbcResultSet.java:2956)
    at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:2962)
    at org.h2.jdbc.JdbcResultSet.getInt(JdbcResultSet.java:306)

I googled for an answer

Make sure to call rs.next(); prior to using any of the getter methods.

But I do call rs.next() ...

Here's my code:

public User getUser(int userId) throws SQLException {
    User u = new User(userId);

    try {
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM invited_users WHERE user_id=" + userId);
        rs.next();

        u.setName(rs.getString("user_name"));

    } catch (SQLException except) {
        JOptionPane.showMessageDialog(null, "Unable to load user! " + except);
    }
    return u;
}

回答1:

The problem was in resultset, it was empty.

Just replace this code

rs.next();

u.setName(rs.getString("user_name"));

with

if (rs.next()) {
    u.setName(rs.getString("user_name"));
}


标签: java h2 h2db