Hello i have a problem with the connection, it is closing the connection while performing a Query. I don´t know what happens D: Here is the configuration:
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;
}
Now, here is the class where i used the pool, First i recieved a connection from Hikari.getConnection(). Then i saved it in "connection"
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();
}
}
And i use the "connection" in 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);
...
At line " Statement stm=connection.createStatement();" an error ocurred
it says :
[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)...
Why is closing the connection?
The structure of your code is rather unclear to me. But I don't think that you want to allocate a Connection in initComponents()
. You should be obtaining a Connection when you need to run a query, and then closing it to return it to the pool.
Something like...
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) {
...
}
The "try with resources" will close the Connection and Statement automatically.
And where SQL.getConnection()
does something like:
public Connection getConnection() throws SQLException {
return Hikari.getConnection();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With