Home  >  Article  >  Database  >  Why Does My Java JDBC Code Throw \'Operation not allowed after ResultSet closed\'?

Why Does My Java JDBC Code Throw \'Operation not allowed after ResultSet closed\'?

Susan Sarandon
Susan SarandonOriginal
2024-11-23 13:41:13363browse

Why Does My Java JDBC Code Throw

Exception: "Operation not allowed after ResultSet closed"

You are encountering a Java JDBC MySQL exception due to the following code:

Statement statement;

public void connect() {
    statement = connection.createStatement();
}

Explanation of the Error:

The statement instance is shared among all database operations. When you execute a SELECT query, it returns a ResultSet object. Once the ResultSet is closed (either explicitly or implicitly), any further operations on the statement will fail with the exception "Operation not allowed after ResultSet closed."

Solution:

To resolve this issue, create a new Statement object for each database operation, such as:

public ResultSet query(String query) throws SQLException {
    if (query.toLowerCase().startsWith("select")) {
        return connection.createStatement().executeQuery(query);
    } else {
        connection.createStatement().executeUpdate(query);
    }
    return null;
}

This ensures that a new Statement is used for each query, preventing the issue of closing the ResultSet from affecting subsequent operations.

The above is the detailed content of Why Does My Java JDBC Code Throw \'Operation not allowed after ResultSet closed\'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn