开发者

Why is this query not returning any results?

开发者 https://www.devze.com 2023-03-30 01:30 出处:网络
I am leaning some Java for school, and for some reason the code below doesn\'t 开发者_如何转开发return any results? Is there a problem with this code? There is a single record in the mysql database, w

I am leaning some Java for school, and for some reason the code below doesn't 开发者_如何转开发return any results? 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.

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.


A ResultSet can only be used while the connection is still open. 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. (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 method names should start with a lower-case letter. GetByID should be getByID and Disconnect should be 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.)


If you want to return the resultSet after closing the connection you have to use CachedRowSet. As StephenC said, your ResultSet is empty after closing the connection.

0

精彩评论

暂无评论...
验证码 换一张
取 消