简体   繁体   English

为什么此查询不返回任何结果?

[英]Why is this query not returning any results?

I am leaning some Java for school, and for some reason the code below doesn't return any results? 我正在学校里学习Java,由于某种原因,下面的代码未返回任何结果? Is there a problem with this code? 这段代码有问题吗? There is a single record in the mysql database, with a studentID (which is int(10) ) of 12. mysql数据库中只有一条记录, studentID为12 int(10) )。

public static ResultSet GetByID(int studentID) {
    // This method loads the mysql driver and establishes the database connection
    Connect();

    ResultSet results = null;

    try {
        String query = "SELECT * FROM student where studentID = ?";

        PreparedStatement statement = Connection.prepareStatement(query);

        statement.setInt(1, studentID);
        results = statement.executeQuery();
    } catch (SQLException ex) {
        LogException(ex);
    } catch (Exception ex) {
        System.out.println(ex);
    }

    // This method terminates the mysql connection.
    Disconnect();

    return results;
}

The calling code is: 调用代码为:

@Override
public ResultSet query() {
    return DB.GetByID(getStudentID()); // this is 12
}

This does not return null, rather just an empty result set. 这不会返回null,而只是返回一个空结果集。

A ResultSet can only be used while the connection is still open. 只能在连接仍处于打开状态时使用ResultSet Read it before you "disconnect". 在“断开连接”之前,请先阅读它。

If fixing that doesn't give you a different result, the most likely cause is that the query didn't match any rows in the table. 如果修复该问题不会给您带来不同的结果,则最可能的原因是查询与表中的任何行都不匹配。


You should get into the habit of closing connections, streams, etc in finally blocks to prevent resource leakage. 您应该养成在finally块中关闭连接,流等的习惯,以防止资源泄漏。 (Your lecturer should have explained that. Check your notes / text book.) (您的讲师应该对此进行了解释。请检查您的笔记/教科书。)


Finally, since you are a beginner, it is worth pointing out that you should always conform to the accepted Java conventions for method naming. 最后,由于您是初学者,因此需要指出的是,对于方法命名,您应始终遵循公认的Java约定。 Java method names should start with a lower-case letter. Java方法名称应以小写字母开头。 GetByID should be getByID and Disconnect should be disconnect . GetByID应该是getByIDDisconnect应该disconnect

(And if your lecturer / tutor doesn't or didn't dock marks for that, he / she should be condemned to writing Visual Basic for the next 5 years for crimes against the Software Engineering industry.) (并且,如果您的讲师/导师没有这样做,也没有因此而停业,则应谴责他/她在未来5年内编写Visual Basic,以打击软件工程行业。)

If you want to return the resultSet after closing the connection you have to use CachedRowSet. 如果要关闭连接返回resultSet 则必须使用CachedRowSet。 As StephenC said, your ResultSet is empty after closing the connection. 正如StephenC所说,关闭连接后,您的ResultSet为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM