java - 为什么即使我不提交也会收到 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
解决方案
这种方法应该像这样工作吗?
是的。仅仅因为您没有提交更改并不意味着您可以执行无效更改。
事务发生在数据库上,而不是应用程序中。因此,您执行的任何操作仍然必须是对那里的数据有效的数据库操作。事务所做的是(显然过度简化)将其全部包装在一个原子的全有或全无操作组中。但是每个操作仍然需要有效。
抛出异常允许开发人员捕获异常并回滚整个事务。这基本上是重点。
推荐阅读
- java - 在 Java 类中映射嵌套的 JSON 值
- python - 如何使用 Python Selenium 在网站上滚动内部滚动条?
- python - 更快地优化 for 循环
- javascript - Angular 和 Stripe 订阅保存付款细节并创建订阅
- typescript - Typeguard 不会缩小类型
- mysql - 使用连接查找最大值的 SQL 查询
- python - 有没有更快的方法将熊猫数据框分成两个互补的部分?
- javascript - 我们可以比较javascript运行时中的数据类型吗
- swift - 如何在 swift struct/class 类型中支持这种初始化?
- java - 从 Firebase 存储中检索和设置图像?