为什么我会得到一个从打开的 MySQL 连接中关闭的 java.sql.PreparedStatement?

1 java mysql jdbc

为什么我java.sql.PreparedStatement从打开的 MySQL 连接中得到一个已关闭的信息?

这是我的代码:

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;



public class MySqlTest1 
{
    Connection connection = null;
    PreparedStatement stmt = null;
    public MySqlTest1() 
    {
        System.out.println("Loading driver...");

        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver loaded!");
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Cannot find the driver in the classpath!", e);
        }
        String url = "jdbc:mysql://localhost:3306/world?autoReconnect=true&useSSL=false";
        String username = "jee";
        String password = "????????";

        System.out.println("Connecting database...");

        try (Connection connection =  DriverManager.getConnection(url, username, password)) 
        {
            if (connection.isClosed())
            {
                System.out.println("Returned connection is closed");
                return;
            }
            System.out.println("Database connected!");
            System.out.println("create statement ...");
            **stmt = connection.prepareStatement("select * from city");**
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }

        System.out.println("Selecting data ...");
        ResultSet rs = null;
        try {
            System.out.println("execute query ...");
            rs = stmt.executeQuery();
            if (rs != null)
            {
                System.out.println("Data selected");
            }
        }
        catch (SQLException ex)
        {
            System.err.println("SQLException: " + ex.getMessage());
            System.err.println("SQLState: " + ex.getSQLState());
            System.err.println("VendorError: " + ex.getErrorCode());
            return;
        }
Run Code Online (Sandbox Code Playgroud)

该代码的结果是

Loading driver...
Driver loaded!
Connecting database...
Database connected!
create statement ...
Selecting data ...
execute query ...
****SQLException: No operations allowed after statement closed.****
SQLState: S1009
VendorError: 0
Run Code Online (Sandbox Code Playgroud)

我也尝试过该声明并研究了它的值,发现“isClosed”是正确的。我查看了 MySQL 日志,但没有发现任何结果。

Mur*_*nik 5

您正在 try-with-resource 块中打开连接。一旦块终止,连接就会关闭,并且隐式地关闭从它创建的所有语句。只需扩展此块以包含该语句的用法,就可以了。