[英]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.