前言
lightdb數據庫是恆生自主研發的面向金融領域的支持集中式和分佈式的國產數據庫,實現基於PostgreSQL,因此也會遵循postgreSQL的一些事務特性。本文章主要說明的特性爲:在一個事務中,如果有一個SQL執行出錯,那麼在這個SQL後面再執行SQL語句就會拋出:“current transaction is aborted, commands ignored until end of transaction block”異常。
示例
本例使用java代碼模擬此特性:
public void lightdbTest() {
try {
Connection connection = TestUtil.openDB();
connection.setAutoCommit(false);
String insertSQl = "insert into table_test(id, name) values (1, '123')";
String updateSQL = "update table_test set name = 'qsfs' where id = 1";
PreparedStatement preparedStatement = connection.prepareStatement(insertSQl);
try {
int num = preparedStatement.executeUpdate();
System.out.println(num);
} catch (Exception e) {
PreparedStatement preparedStatement1 =connection.prepareStatement(updateSQL);
int num = preparedStatement1.executeUpdate();
System.out.println(num);
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
說明
- 開啓隱式事務,整個方法在一個事務中,此示例中要執行兩個SQL。
- 第一條insert語句執行的時候會拋異常。
- 異常捕獲之後執行update語句,此時會拋異常如下:
可以看到不僅拋出了事務異常,同時把執行insert語句的異常也拋出來了,這就是postgreSQL數據庫的特性,換做mysql或者oracle這個非pg系的數據庫update語句會正常執行。
解決辦法
- 可以將隱式事務改爲顯示事務,SQL執行完自動提交。
- 可以在第一個SQL執行出錯之後做事務提交或迴歸,然後重新開啓事務執行第二個SQL。
- 整個事務回滾,不執行第二個SQL。