您好我有一个连接问题,它正在执行查询时关闭连接。我不知道会发生什么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);
...
在“语句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)...
为什么要关闭连接?
最佳答案
您的代码结构对我来说还不太清楚。但是我不认为您想在initComponents()
中分配一个Connection。当您需要运行查询时,应该获得一个Connection,然后将其关闭以将其返回到池中。
就像是...
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) {
...
}
“尝试使用资源”将自动关闭连接和语句。
而
SQL.getConnection()
的作用类似于:public Connection getConnection() throws SQLException {
return Hikari.getConnection();
}