【问题标题】:Updating multiple tables in MySQL using transactions使用事务更新 MySQL 中的多个表
【发布时间】:2016-04-20 19:46:47
【问题描述】:

在java中,如果我想在同一个数据库的多个表中插入数据作为事务,那么我应该使用相同的连接还是为每个表创建连接?

insertInTable(){

insetInTable1();
insertInTable2()

}

insetInTable1(){
//get new connection , insert commit
}

insetInTable2(){
//get new connection , insert commit
}

或者

insertInTable(){

Connection conn = getConnection();
insetInTable1(conn);
insertInTable2(conn)

conn.commit();
}

insetInTable1(Connection conn){
//insert
}

insetInTable2(Connection conn ){
//insert 
}

假设两个表都在同一个数据库中。

是否可以跨方法发送相同的连接?

【问题讨论】:

    标签: java mysql sql


    【解决方案1】:

    您可以使用带有参数的storedprocedure mysql...并在开始事务中插入所有代码

    您也可以使用此代码JDBC

    dbConnection.setAutoCommit(false); //transaction block start
    
    String insertTableSQL = "INSERT INTO DBUSER"
                + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
                + "(?,?,?,?)";
    
    String updateTableSQL = "UPDATE DBUSER SET USERNAME =? "
                + "WHERE USER_ID = ?";
    
    preparedStatementInsert = dbConnection.prepareStatement(insertTableSQL);
    preparedStatementInsert.setInt(1, 999);
    preparedStatementInsert.setString(2, "mkyong101");
    preparedStatementInsert.setString(3, "system");
    preparedStatementInsert.setTimestamp(4, getCurrentTimeStamp());
    preparedStatementInsert.executeUpdate(); //data IS NOT commit yet
    
    preparedStatementUpdate = dbConnection.prepareStatement(updateTableSQL);
    preparedStatementUpdate.setString(1, "A very very long string caused DATABASE ERROR"); 
    preparedStatementUpdate.setInt(2, 999);
    preparedStatementUpdate.executeUpdate(); //Error, rollback, including the first insert statement.
    
    dbConnection.commit(); //transaction block end
    

    【讨论】:

    • 我们没有使用存储过程,因此它不会绑定到特定的数据库。
    【解决方案2】:

    肯定是后者,即由单个开始/提交包围的两个插入语句。您不能在多个连接之间保留事务。

    ...嗯,使用 Open-XA 是可能的,但很难通过常规 J​​ava 代码进行管理,而且无论如何这里没有任何意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2014-01-30
      • 2016-07-26
      • 1970-01-01
      • 2019-12-30
      • 2018-05-11
      • 1970-01-01
      相关资源
      最近更新 更多