在 transactionscope 中打开 sql 连接是否重要

发布于 2024-08-15 20:33:58 字数 426 浏览 4 评论 0 原文

我创建了一个 sqlconnection,CN1。然后这个CN1就打开了。稍后在代码中有一个事务范围。如果我在此 CN1 连接上执行 sql 命令,这是否在事务内?

代码如下所示;

SqlConnection cn1 = new SqlConnection();
cn1.Open(); //connection opened when there is no ambient transaction.
...

using(TransactionScope scope = new TransactionScope())
{
  SqlCommand cmd; //a typical sql command.

  ...

  cmd.ExecuteNonQuery(); //Is this command within transaction?
  ...
}

I created a sqlconnection, CN1. Then this CN1 is opened. Later in the code there is a transactionscope. If I execute a sql command on this CN1 connection, is this within transaction?

Code looks like this;

SqlConnection cn1 = new SqlConnection();
cn1.Open(); //connection opened when there is no ambient transaction.
...

using(TransactionScope scope = new TransactionScope())
{
  SqlCommand cmd; //a typical sql command.

  ...

  cmd.ExecuteNonQuery(); //Is this command within transaction?
  ...
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请爱~陌生人 2024-08-22 20:33:58

必须在 TransactionScope 内打开连接,以确保连接已注册到事务中。

这可以在 connection.Open 上方的注释中找到="nofollow noreferrer">这个 MSDN 示例。

It is a MUST to open the connection within the TransactionScope to ensure that the connection is enrolled in the transaction.

This is found in the comment just above the connection.Open in this MSDN example.

沙沙粒小 2024-08-22 20:33:58
  1. 否,命令不在事务中执行
  2. 在范围内打开连接或使用 SqlConnection 实例的 EnlistTransaction 方法。请参阅我在不同线程中的答案
  1. No, command is not executed in transaction
  2. Open connection inside the scope or use EnlistTransaction method of SqlConnection instance. See my answer in different thread.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文