我试图从h2 db获取值,但始终收到此错误
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)
我用Google搜索了答案
确保调用rs.next();在使用任何getter方法之前。
但我确实叫rs.next()......
这是我的代码:
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;
}
答案 0 :(得分:12)
问题出在结果集中,它是空的。
只需替换此代码
rs.next();
u.setName(rs.getString("user_name"));
与
if (rs.next()) {
u.setName(rs.getString("user_name"));
}