I have an ArrayList in Java and I want to insert it into my database but it's always showing me this error code
Exception in thread "main" java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
And I don't know why it's happening, I have tried many fix in the internet but non of it is working
here's my code snipset
Connection con = db.getConnection();
try{
for(Stock element: listStock){
if(element.getKodeSaham().equals(getKode_saham())){
int hargaSaham = element.getHarga();
int harga = (lot*100) * hargaSaham;
for(Transaction trans : listTransaksi){
//System.out.println(trans.getKodeSaham());
PreparedStatement p1 = con.prepareStatement("INSERT INTO history (id_transaction, kode_saham, lot, harga, username, status, lot_sell_check) VALUES(NULL,'"+getKode_saham()+"','"+getLot()+"','"+harga+"','"+getUsername()+"', 'Buy','"+getLot()+"')");
p1.executeUpdate();
}
}
}
}finally {
con.close();
}
And here's my database connection:
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/tes";
static final String USER = "root";
static final String PASS = "";
private static Connection connection;
public static Connection getConnection() throws SQLException{
if (connection == null){
connection = createConnection();
}
return connection;
}
private static Connection createConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(db.class.getName()).log(Level.SEVERE, null, ex);
}
return connection;
}