gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:36:08 24 4
gpt4 key购买 nike

为什么我得到一个 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;
}

该代码的结果是

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

我也尝试过使用 Statement 并查看它的值,发现“isClosed”是正确的。我查看了 MySQL 日志,但一无所获。

最佳答案

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

关于java - 为什么我得到一个从打开的 MySQL 连接关闭的 java.sql.PreparedStatement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com