简体   繁体   English

处理多个Mysql数据库连接失败

[英]Handle Multiple Mysql Database connection Failure

I'm Stuck at the situation where more than 1 Database connection needs to be handle. 我被困在需要处理多个1个数据库连接的情况。 For example : 例如 :

function update_user()
{
 #Establish connection with DB1
 #Update the user

 # Close connection with DB1
 #Establish connection with DB2
 #Update the user

 # Close connection with DB2
 #Establish connection with DB3
 #Update the user

}

In the above Algorithm I have to establish connection one by one and update the user from the corresponding tables. 在上述算法中,我必须一个接一个地建立连接,并从相应的表中更新用户。

My Question is : What happened when any of the DB connection failed and how can i roll back for the above executions ? 我的问题是当任何数据库连接失败时会发生什么,我如何回滚上述执行? For Example if DB1 Connection executes successfully and DB2 connection failed than what is the best way to roll back the execution of DB1. 例如,如果DB1连接成功执行而DB2连接失败,那么回滚DB1执行的最佳方法是什么。

My Proposed Solution : I think i can use the PHP to handle this, i just need to maintain the Array with updated records and ids. 我建议的解决方案 :我想我可以使用PHP来处理此问题,我只需要使用更新的记录和ID维护Array。 and Execute the Update query again for DB1 connection. 并再次执行Update查询以进行DB1连接。 But this case also fails when that time the DB1 Connection also got failed. 但是,当DB1连接也失败时,这种情况也会失败。 So i can't handle it with PHP. 所以我不能用PHP处理它。 what could be the solution ? 有什么解决方案?

I would suggest using transactions within MySQL. 我建议在MySQL中使用事务。

I would suggest starting a transaction after opening each connection (for each connection) and committing them when all the updates have succeeded or rolling them all back when they fail. 我建议在打开每个连接(对于每个连接)之后启动事务,并在所有更新成功后提交它们,或者在失败时全部回滚。 This will ensure no rows are updated unless all of the updates succeed. 除非所有更新成功,否则这将确保没有行被更新。

For more information on transactions, see here: https://dev.mysql.com/doc/refman/5.0/en/commit.html 有关交易的更多信息,请参见: https : //dev.mysql.com/doc/refman/5.0/en/commit.html

Pseudo Code: 伪代码:

# Try
    # Establish connection with DB1
    # Create a transaction for DB1 connection 
    # Update the user

    # Establish connection with DB2
    # Create a transaction for DB2 connection
    # Update the user

    # Establish connection with DB3
    # Create a transaction for DB3 connection
    # Update the user

    # Commit all transactions
# Catch
    # Rollback all transactions, rethrow exception
# Finally
    # Close all connections

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM