您好我的连接有问题,它正在执行查询时关闭连接。我不知道会发生什么D: 这是配置:
private static HikariDataSource Hikari;
public static String ID_Usuario;
public void connectToDatabase() {
Hikari = new HikariDataSource();
Hikari.setDriverClassName("com.mysql.jdbc.Driver");
Hikari.setJdbcUrl("jdbc:mysql://localhost:3306/bank");
Hikari.setUsername("root");
Hikari.setPassword("");
Hikari.setMaximumPoolSize(5);
Hikari.setConnectionTimeout(300000);
Hikari.addDataSourceProperty("cachePrepStmts", "true");
Hikari.addDataSourceProperty("prepStmtCacheSize", "250");
Hikari.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
Hikari.setConnectionTestQuery("SELECT 1");
}
public HikariDataSource getHikari(){
return Hikari;
}
现在,这里是我使用池的类,首先我收到了来自Hikari.getConnection()的连接。然后我把它保存在“连接”
中Pool HikariPool;
HikariDataSource Hikari;
Connection connection;
public SQL() {
initComponents();
}
public void initComponents(){
HikariPool= new Pool();
HikariPool.connectToDatabase();
Hikari=HikariPool.getHikari();
try{
connection= Hikari.getConnection();
}catch(SQLException e){
e.printStackTrace();
}
}
我在validateLogin()
中使用“连接”public int validateLogin(String nip){
int validation=0;
String SQL="SELECT * FROM bank.account WHERE No_Account='"+account+"'
AND NIP='"+nip+"'";
try{
Statement stm=Conexion.createStatement();
ResultSet rs= stm.executeQuery(SQL);
...
在行“Statement stm = connection.createStatement();”发生错误
它说:
[AWT-EventQueue-0] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-0
- is starting.
java.sql.SQLException: Connection is closed at
com.zaxxer.hikari.pool.ProxyConnection$ClosedConnection$1.invoke
(ProxyConnection.java:468)
at com.sun.proxy.$Proxy0.createStatement(Unknown Source)...
为什么关闭连接?
答案 0 :(得分:2)
我的代码结构对我来说还不太清楚。但我不认为你想在initComponents()
中分配一个连接。您应该在需要运行查询时获取连接,然后关闭它以将其返回到池中。
像...一样的东西。
public int validateLogin(String nip) {
int validation=0;
String SQL="SELECT * FROM bank.account WHERE No_Account='"+account+"'
AND NIP='"+nip+"'";
try (Connection conn = SQL.getConnection();
Statement stm = conn.createStatement()) {
ResultSet rs = stm.executeQuery(SQL);
...
}
catch (SQLException e) {
...
}
"尝试使用资源"将自动关闭Connection和Statement。
SQL.getConnection()
的作用类似于:
public Connection getConnection() throws SQLException {
return Hikari.getConnection();
}