代码之家  ›  专栏  ›  技术社区  ›  amir

jdbc连接中executeQuery出错[重复]

  •  -2
  • amir  · 技术社区  · 10 年前

    我的数据库中有一个表,它有两列 id name 我为这两列的get和set值编写了一个类。 我的getCourseName是:

    public String getCourseName(int id) throws SQLException {
        String SQL = "select * from courses where id ="+id;
        Connection con = c.getCon();
        Statement statement = con.createStatement();
        ResultSet res = statement.executeQuery(SQL);
        String nm = res.getString("name");
    
        return nm;
    }
    

    当我运行这个函数时,它的show error http status 500异常:

    javax.servlet.ServletException: java.sql.SQLException: Before start of result set
    
    3 回复  |  直到 10 年前
        1
  •  2
  •   Eran    10 年前

    你忘了打电话 res.next(); 之后 executeQuery 。此调用使结果集前进以指向返回的第一行(假设返回了任何行)。对它的每个附加调用都会将结果集推进到下一行。

    ResultSet res = statement.executeQuery(SQL);
    String nm = null;
    if (res.next()) {
      String nm = res.getString("name");
    }
    
        2
  •  1
  •   SparkOn    10 年前

    基本错误 ResultSet res = statement.executeQuery(SQL); 这给你一个 ResultsetObject

    现在问题来了什么是 ResultSet

    ResultSet对象保持光标指向其当前数据行。最初,光标位于第一行之前。next方法将光标移动到下一行,因为当ResultSet对象中没有更多行时,它返回false,所以可以在while循环中使用它来遍历结果集。

    因此,这意味着您需要迭代获得的resultsetObject以获得列值。 像这样的东西

    while(resultSetObject.next())
    {
      String name = resultSetObject.getString("yourColumnName");
    }
    

    *注释 始终尝试使用 PreparedStatement 而不是 Statement 避免 sql-injection

    所以在这种情况下,它会是这样的

    String SQL = "select * from courses where id = ?";
    PreparedStatement statement = con.prepareStatement(sql);
    statement.setInt(1,id);
    ResultSet res = statement.executeQuery();
    
        3
  •  0
  •   Thusitha Thilina Dayaratne    10 年前
    public String getCourseName(int id) throws SQLException {
        String SQL = "select * from courses where id ="+id;
        Connection con = c.getCon();
        Statement statement = con.createStatement();
        ResultSet res = statement.executeQuery(SQL);
        String nm = null;
        if(res.next())
          nm = res.getString("name");
        con.close();
        return nm;
    }