简体   繁体   English

在新连接中提交交易

[英]Commit transaction within new connection

Given the following code: 给出以下代码:

        var Connection = new MySqlConnection("***");
        MySqlCommand cmd1 = new MySqlCommand("query1", Connection);
        MySqlCommand cmd2 = new MySqlCommand("query2", Connection);
        Connection.Open();
        var transaction = Connection.BeginTransaction();
        cmd1.Transaction = transaction;
        cmd2.Transaction = transaction;
        var result1 = cmd1.ExecuteNonQuery();
        Connection.Close();
        // Connection with MySql lost: Initiate new Connection
        Connection = new MySqlConnection("***");
        Connection.Open();
        cmd2.Connection = Connection;
        var result2 = cmd2.ExecuteNonQuery();
        //transaction.Commit();

If I try to commit transaction in the last line, I get "Connection must be valid and open to commit transaction" error as transaction is still pointing to the old connection. 如果我尝试在最后一行提交事务 ,则会出现“连接必须有效并且可以打开以提交事务”错误,因为事务仍指向旧连接。

What's the best option to commit a transaction in this scenario (Connection initialized in the middle of a transaction)? 在这种情况下(在事务中间初始化连接),提交事务的最佳选择是什么?

Should I retry from the beginning? 我应该从头开始重试吗?

Transactions end as soon as the connection is lost. 连接断开后,事务将立即终止。 You can't have a transaction that spans multiple connections. 您不能进行跨多个连接的事务。 You have to either commit or rollback prior to closing the connection. 在关闭连接之前,您必须提交或回滚。

You can reuse the same connection for multiple statements, as long as you don't close it. 只要不关闭同一连接,就可以将其用于多个语句。 When you open a new connection, you have to start a new transaction too. 当打开一个新的连接时,您也必须开始一个新的事务。

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

相关问题 C#MySQL提交事务不起作用(连接必须有效并且可以提交事务) - C# MySQL commit transaction is not working (Connection must be valid and open to commit transaction) 在transaction.Commit或Rollback之后连接对象会发生什么 - What happens to connection object after transaction.Commit or Rollback SQL 事务提交使连接处于损坏状态 (c#) - SQL Transaction commit leaves connection in corrupt state (c#) 使用静态数据库连接进行事务提交和回滚c# - Transaction Commit and Rollback with Static DB Connection c# 在没有参与事务的情况下在TransactionScope范围内打开新的数据库连接 - Open new database connection in scope of TransactionScope without enlisting in the transaction TransactionFailureException:无法提交事务 - TransactionFailureException: Unable to commit transaction 如果部分交易失败,则提交交易 - Commit a transaction if part of it fails ExecuteNonQueryAsync并在SQL事务中提交 - ExecuteNonQueryAsync and commit in a SQL Transaction 在 foreach 循环中提交事务 - Commit transaction in foreach loop 连接必须有效并且打开才能在尝试执行失败的查询时提交sqllite数据库的事务 - Connection must be valid and open to commit transaction for sqllite database while retrying to execute the failed query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM