boolean autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); String sql = "insert into article values(null,?,?,?,?,now(),?)"; PreparedStatement pstmt = DB.prapareStmt(conn,sql,Statement.RETURN_GENERATED_KEYS); int rootId = -1 ; pstmt.setInt(1,0); pstmt.setInt(2,rootId); pstmt.setString(3,title); pstmt.setString(4,cont); pstmt.setInt(5,1); pstmt.executeUpdate(); ResultSet rsKey = pstmt.getGeneratedKeys(); rsKey.next(); rootId = rsKey.getInt(1); Statement stmt = DB.createStmt(conn); stmt.executeUpdate("update article set rootid = 1 where id = " + rootId); conn.commit(); conn.setAutoCommit(autoCommit); DB.close(pstmt); DB.createStmt(conn);
commit
void commit() throws SQLException
-
使所有上一次提交/回滚后进行的更改成为持久更改,并释放此
Connection
对象当前持有的所有数据库锁。此方法只应该在已禁用自动提交模式时使用。
getAutoCommit
boolean getAutoCommit() throws SQLException
-
获取此
Connection
对象的当前自动提交模式。 -
-
-
返回:
-
此
Connection
对象的自动提交模式的当前状态
-
此
setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException
-
将此连接的自动提交模式设置为给定状态。如果连接处于自动提交模式下,则它的所有 SQL 语句将被执行并作为单个事务提交。否则,它的 SQL 语句将聚集到事务中,直到调用
commit
方法或rollback
方法为止。默认情况下,新连接处于自动提交模式。提交发生在语句完成时。语句完成的时间取决于 SQL 语句的类型:
- 对于 DML 语句(比如 Insert、Update 或 Delete)和 DDL 语句,语句在执行完毕时完成。
- 对于 Select 语句,语句在关联结果集关闭时完成。
- 对于
CallableStatement
对象或者返回多个结果的语句,语句在所有关联结果集关闭并且已获得所有更新计数和输出参数时完成。
注:如果在事务和自动提交模式更改期间调用此方法,则提交该事务。如果调用
setAutoCommit
而自动提交模式未更改,则该调用无操作(no-op)。 -
-
-
参数:
-
autoCommit
- 为true
表示启用自动提交模式;为false
表示禁用自动提交模式
-