在C# .Net 2.0中进行交易的最佳实践是什么?应该使用哪些类?需要注意什么陷阱等。所有的提交和回滚操作。我刚开始一个项目,可能需要在向数据库插入数据时执行一些事务。欢迎任何关于交易的基础知识的回应或链接。
在C# .Net 2.0中进行交易的最佳实践是什么?应该使用哪些类?需要注意什么陷阱等。所有的提交和回滚操作。我刚开始一个项目,可能需要在向数据库插入数据时执行一些事务。欢迎任何关于交易的基础知识的回应或链接。
主要有两种类型的事务:连接事务和环境事务。连接事务(例如SqlTransaction)直接绑定到数据库连接(例如SqlConnection),这意味着您必须不断地传递连接 - 在某些情况下可以,但不允许“创建/使用/释放”用法,并且不允许跨数据库工作。以下是一个示例(格式化以便显示清晰)
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
另一种选择是环境事务;在.NET 2.0中引入了TransactionScope对象(System.Transactions.dll),允许在一系列操作中使用(适当的提供程序将自动注册到环境事务)。这使得将其追加到现有的(非事务性)代码中变得容易,并且可以与多个提供程序通信(尽管如果您与多个提供程序通信,则会涉及DTC)。
例如:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
tran.Rollback();
这一行不是必须的吗?至少对于大多数 IDbTransaction
实现来说是这样的吗? - astefprotected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection1 = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
{
connection1.Open();
// Start a local transaction.
SqlTransaction sqlTran = connection1.BeginTransaction();
// Enlist a command in the current transaction.
SqlCommand command = connection1.CreateCommand();
command.Transaction = sqlTran;
try
{
// Execute two separate commands.
command.CommandText =
"insert into [doctor](drname,drspecialization,drday) values ('a','b','c')";
command.ExecuteNonQuery();
command.CommandText =
"insert into [doctor](drname,drspecialization,drday) values ('x','y','z')";
command.ExecuteNonQuery();
// Commit the transaction.
sqlTran.Commit();
Label3.Text = "Both records were written to database.";
}
catch (Exception ex)
{
// Handle the exception if the transaction fails to commit.
Label4.Text = ex.Message;
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
// Throws an InvalidOperationException if the connection
// is closed or the transaction has already been rolled
// back on the server.
Label5.Text = exRollback.Message;
}
}
}
}
如果你只需要它用于数据库相关的工作,一些对象关系映射器(例如NHibernate)默认支持事务。
这取决于您的需求。对于基本的SQL事务,您可以尝试使用BEGIN TRANS和COMMIT TRANS在代码中执行TSQL事务。这是最简单的方式,但它确实有一定的复杂性,并且您必须小心正确提交(和回滚)。
我会使用类似于
SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
...
Do SQL stuff here passing my trans into my various SQL executers
...
trans.Commit // May not be quite right
}
using
,并且事务将始终提交或回滚(取决于您告诉它要做什么)。我们面临的最大问题是确保它始终提交。使用确保了事务范围的限制。