从 SQLConnection 对象或从 SqlCommand 对象调用 BeginTransaction 之间有区别吗?

Hao*_*est 3 c# transactions

所以我有这个来自 c# 的 sql 将购买信息插入一个表(sql server 2005),并将购买项目(多个)插入另一个表。

我希望通过调用 BeginTransaction 在事务中运行 2 个插入语句。

我注意到我可以从 SqlConnection 对象或 SqlCommand 对象中做到这一点。我的胆量告诉我,我应该通过连接对象来完成它,因为我将为每个插入使用 1 个命令对象,但它们都共享相同的连接。

我对吗?

一般来说,两者有区别吗?

sam*_*tin 7

从连接 (BeginTransaction) 创建一个 SqlTransaction,然后将其传递给每个 SqlCommand 对象。有一个构造函数将 SqlTransaction 作为参数,或者只设置 SqlCommand.Transaction 属性。

像这样:(抱歉在 iPad 上格式化困难)

var tran = db.BeginTransaction();
try {

  SqlCommand com = new SqlCommand(...., tran);
  // or.  
  com.Transaction=tran;

  // do the work, eg execute SQL 

  // finally commit the changes
  tran.Commit();
}
catch
{
  tran.Rollback();
}
Run Code Online (Sandbox Code Playgroud)