【问题标题】:JDBC Error: Before start of result set [duplicate]JDBC错误:结果集开始之前[重复]
【发布时间】:2014-05-05 21:37:23
【问题描述】:

我在 Java eclipse 中有一条错误消息。我在 MySql 中有一个数据库,它有列字符串 user_name、int id_time、int id_desk、int user_password。我想使用一行的列数据

public ArrayList showReservation(String user_name) throws SQLException{

    // array list keeps the information
    ArrayList<String> showReservation = new ArrayList<String>();
    try{

        String getReservationSql = "SELECT * FROM reservation " 
                +"WHERE user_name ='" + user_name + "';";
        rs = stmt.executeQuery(getReservationSql);

        // first element of the array list keeps user name
        showReservation.add("" + rs.getString("user_name")); 

        // second element of the array list keeps id of the desk which is selected by user
        showReservation.add("" + rs.getInt("id_time")); 

        // third element of the array list keeps id of the time interval which is selected by user
        showReservation.add("" + rs.getInt("id_desk"));  

        // forth element of the array list keeps user's password which is generated automatically in a controller class
        showReservation.add("" + rs.getInt("user_password")); 

    }catch (SQLException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
    return showReservation;
}

但是当我运行此代码时出现错误:在结果集开始之前。 我该如何解决这个错误? 谢谢

【问题讨论】:

标签: java mysql jdbc


【解决方案1】:

您永远不会前进到ResultSet 中的第一个结果。使用the next() method 前进到下一条记录,当没有更多记录时返回false

rs = stmt.executeQuery(getReservationSql);
while (rs.next())
{
   // Make your calls to getString and getInt here
}

【讨论】:

    【解决方案2】:

    在尝试调用任何ResultSet getter 方法之前使用next

    rs = stmt.executeQuery(getReservationSql);
    if (rs.next()) {
       ...
    }
    

    旁白:考虑Using Prepared Statements

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2013-10-01
      • 2022-01-18
      • 2011-01-16
      相关资源
      最近更新 更多