为什么我从已打开的MySQL连接中关闭了java.sql.PreparedStatement
?
这是我的代码:
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
我也尝试过该声明,并研究了它的价值观,并发现" isClosed"是真的。 我查看了MySQL日志但没有找到任何内容。
答案 0 :(得分:4)
您正在尝试使用资源块中打开连接。块终止后,将关闭连接,并隐式地关闭从中创建的所有语句。只需扩展此块以包含语句的用法,您应该没问题。