Home > Database > Mysql Tutorial > body text

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

Susan Sarandon
Release: 2024-11-23 13:41:13
Original
365 people have browsed it

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();
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template