Search code examples
javamysqlexceptionjdbccommit

Why do I get a SQLException even if I don't commit?


I have a method to check how commit is work. I'm trying to set wrong values to get exception and check when it throws. I thought it will be after commit ,but it throws when I use the executeUpdate method. Is this method supposed to work like this?

public void check(){
    String query = "Insert into user_info(login,userPassword,userType,userEmail)values(?,?,?,?);";
    Connection connection = null;
    PreparedStatement statement = null;
    try{
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/taksi_online","Bruce","givanchy");
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(query);
        statement.setString(1,"asdasqqqqqqq");
        statement.setString(2,"sff");
        statement.setString(3,"client");
        statement.setString(4,"qweq");
        System.out.println(statement.executeUpdate());
    } catch (SQLException e) {
        System.out.println("Error message "+e.getMessage());
        System.out.println("Error code "+e.getErrorCode());
        System.out.println("Sql state is "+e.getSQLState());
        // I get error at this place
    }finally {
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    System.out.println("after");
    try {
        //but I thought I should get it here after commit
        connection.commit();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }finally {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
Error message Duplicate entry 'asdasqqqqqqq' for key 'user_info.login'
Error code 1062
Sql state is 23000
after

Solution

  • Is this method supposed to work like this?

    Yes. Just because you haven't committed the changes doesn't mean you can perform invalid changes.

    The transaction happens on the database, not in the application. So any operations you execute are still going to have to be valid database operations for the data that's there. What the transaction does is (over-simplifying obviously) wrap it all in an atomic all-or-nothing group of operations. But each operation still needs to be valid.

    Throwing the exception allows the developer to catch the exception and roll back the entire transaction. Which is essentially the whole point.