0

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;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Your first code closes the connection, while the second code tries to reuse the connection and is unaware if the connection was already closed. Please don't write such a brittle connection manager, instead use a connection pool like HikariCP, or **always** return a **new** connection. – Mark Rotteveel Jan 11 '23 at 08:20
  • Incidentally, you should NEVER use String concatenation to build SQL statements with user input - you are laying yourself open to SQL Injection attacks. Instead, learn to use parameters (eg `VALUES (null, ?, ?, ?, ?)`, and set them with `con.setString`, etc). See https://stackoverflow.com/a/8264648/681444 – racraman Jan 11 '23 at 09:16

0 Answers0