Java jdbc连接中的executeQuery出错

Java jdbc连接中的executeQuery出错,java,mysql,jdbc,Java,Mysql,Jdbc,我的数据库中有一个表,它有两列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.createStat

我的数据库中有一个表,它有两列
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;
}
运行此函数时,其显示错误http status 500异常:

javax.servlet.ServletException: java.sql.SQLException: Before start of result set

你忘了调用
res.next()
executeQuery
之后。此调用使结果集前进,指向返回的第一行(假设返回了任何行)。对它的每次额外调用都会将结果集前进到下一行

ResultSet res = statement.executeQuery(SQL);
String nm = null;
if (res.next()) {
  String nm = res.getString("name");
}

基本错误
ResultSet res=statement.executeQuery(SQL)这将为您提供一个
ResultsetObject

现在的问题是什么是
ResultSet

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

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

while(resultSetObject.next())
{
  String name = resultSetObject.getString("yourColumnName");
}
String SQL = "select * from courses where id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1,id);
ResultSet res = statement.executeQuery();
*注意始终尝试使用
PreparedStatement
而不是
语句
,以避免
sql注入

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

while(resultSetObject.next())
{
  String name = resultSetObject.getString("yourColumnName");
}
String SQL = "select * from courses where id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1,id);
ResultSet res = statement.executeQuery();