SQLite database refuses to update and I'm not sure why

Viewed 54

I'm using these two methods in order to update the balance of a bank app I'm writing, but the database refuses to update and I'm not sure why.

Function for getting how much to add:

public void addIncome(String cardNum,Scanner scanner){
    System.out.println("Enter income: ");
    int income = scanner.nextInt();
    scanner.nextLine();
    dataBase.addBalance(income,cardNum);
}

Prepared statement and function for query:

private final String ADD_BALANCE = ("UPDATE card SET balance=balance+? WHERE number=?");

public void addBalance(int amount, String number){
       try (Connection con = this.dataSource.getConnection();
         final var sql = con.prepareStatement(ADD_BALANCE)){
           sql.setInt(1, amount);
           sql.setString(2,number);
           sql.executeUpdate();
       }catch (SQLException throwables) {
           throwables.printStackTrace();
       }
}
1 Answers

You're missing a call to commit, meaning the transaction will implicitly rollback when the connection is closed (at the end of the try).

try (Connection con = this.dataSource.getConnection();
     final var sql = con.prepareStatement(ADD_BALANCE)) {
    sql.setInt(1, amount);
    sql.setString(2, number);
    sql.executeUpdate();
    con.commit(); // HERE
}
Related