Here is my Database.java. It does works "flawless" for what I want, but the problem is that it just not closing the connections with "connection.close()".
package com.example.testDB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class Database{
private Connection connection;
private final String host = "host";
private final String database = "databasename"
private final int port = 1234;
private final String user = "user";
private final String pass = "password";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
}
public void insert() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Statement stmt;
String sql = "INSERT INTO TEST_TABLE (COLUMN1, COLUMN2, COLUMN3) VALUES ('TEST','TEST','TEST')";
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" + status);
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
connection.close();
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
}
I don't know why this is happening, or if this is how I should do it in the first place, I got this class model from a tutorial on the internet and it does works, but has this problem of the connections not closing somehow. What am I doing wrong?