首页 > 解决方案 > 为什么即使我不提交也会收到 SQLException?

问题描述

我有一种方法来检查提交是如何工作的。我试图设置错误的值来获取异常并检查它何时抛出。我认为它会在提交之后,但是当我使用该executeUpdate方法时它会抛出。这种方法应该像这样工作吗?

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

标签: javamysqlexceptionjdbccommit

解决方案


这种方法应该像这样工作吗?

是的。仅仅因为您没有提交更改并不意味着您可以执行无效更改。

事务发生在数据库上,而不是应用程序中。因此,您执行的任何操作仍然必须是对那里的数据有效的数据库操作。事务所做的是(显然过度简化)将其全部包装在一个原子的全有或全无操作组中。但是每个操作仍然需要有效。

抛出异常允许开发人员捕获异常并回滚整个事务。这基本上是重点。


推荐阅读