如果使用TransactionScope
,它应该做工精细,但范围必须环绕连接(S):
using(TransactionScope tran = new TransactionScope()) {
using(SqlConnection conn = new SqlConnection(cs)) {
// either multiple commands on one connection
using(SqlCommand cmd = conn.CreateCommand()) {
// etc
}
using(SqlCommand cmd = conn.CreateCommand()) {
// etc
}
}
using(SqlConnection conn = new SqlConnection(cs)) {
// or a separate connection
using(SqlCommand cmd = conn.CreateCommand()) {
// etc
}
}
tran.Complete();
}
有是an edge case where a TransactionScope
can fail导致后来的命令来运行没有交易。
或者,对于单个连接使用SqlTransaction
,但请记住将事务(从连接)关联到每个命令。
你如何在代码中使用事务范围(使用语句或try/catch)? – Goran 2009-12-01 12:26:00
是的Goran,我使用“using”语句,如: 使用(TransactionScope scope = new TransactionScope()) 封装在try/catch块中。 并且对SP的调用在此范围内 – 2009-12-01 12:36:44
我不明白这是怎么回事。如何在OnExit方法中添加回滚调用?这应确保在停止控制台应用程序并且事务未完成时调用回滚。 – Goran 2009-12-01 12:46:11