本文通过实例介绍如何通过jdbc连接GBase8s,实现事务的手动提交。
对多个SQL指令进行操作,只有这些指令都成功时,才能认为整个操作是完成的,这样的操作称为”事务操作“。如果一个SQL指令操作失败,之前的各个操作都要取消,这种取消动作称为”回滚 (rollback)“。
1、首先,工程中引入GBase8s驱动包文件。
2、编写jdbc访问GBase8s存储过程用例:
public static void main(String[] args) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String url = “jdbc:gbasedbt-sqli://localhost:19088/testdb”;
String user = “gbasedbt”;
String password = “GBase123”;
String sql1 = “insert into test1 values(123);”;
String sql2 = “insert into test1 values(234);”;
String sql3 = “insert into test1 values(345);”;
String sql4 = “select * from test1;”;
try {
Class.forName("com.gbasedbt.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
System.out.println("成功连接数据库");
//关闭自动提交
connection.setAutoCommit(false);
//插入数据“123”
preparedStatement = connection.prepareStatement(sql1);
preparedStatement.executeUpdate();
//执行回滚
connection.rollback();
//插入数据“234”
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();
//插入数据“234”
preparedStatement = connection.prepareStatement(sql3);
preparedStatement.executeUpdate();
//执行提交
connection.commit();
//查询结果
preparedStatement = connection.prepareStatement(sql4);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
}
3、结果分析:
JDBC事务操作默认是自动提交的,一条对数据库的更新表达式代表一项事务操作,操作成功后,系统会自动调用commit()来提交,否则会调用rollback()来回滚。
如果想取消自动提交可以调用setAutoCommit(false),回复自动提交则可以设置其实参为true。取消自动提交可以灵活地将多个表达式作为一个事务,然后使用commit()来提交,如果出现异常可以使用rollback()来回滚。