简体   繁体   English

什么与C#中的SQL回滚事务等效?

[英]what is there equivalent to rollback transaction of SQL in c#?

if in a transaction any error occurs 如果在交易中发生任何错误

sql will rollback the process. sql将回滚该过程。

BEGIN TRANSACTION

 COMMIT

 IF @@TRANCOUNT > 0
        ROLLBACK

END TRANSACTION

How i can do the same in asp.net C#? 我如何在asp.net C#中做同样的事情?

Check below to see how to implement Implicit Transaction using Transaction Scope which will give you transaction in C#. 检查以下内容,以了解如何使用Transaction Scope实现隐式事务,这将为您提供C#事务。 If you call the Complete method for the TransactionScope it will be commited otherwise rolledback. 如果您为TransactionScope调用Complete方法,则将被提交,否则将被回滚。

http://msdn.microsoft.com/en-us/library/ee818746(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/ee818746(v=vs.110).aspx

The following snippet shows the general idea: 以下代码段显示了一般思路:

using (SqlConnection connection = new SqlConnection("connection string"))
using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlCommand command = new SqlCommand("command text", connection) { Transaction = transaction })
{
    connection.Open();
    try
    {
        command.ExecuteNonQuery();
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
}

If the command fails to execute and throws any exception, the transaction will be rolled back. 如果命令执行失败并引发任何异常,则事务将回滚。

I don't really find your question clear enough. 我真的不太清楚你的问题。 Here is something I would like to share. 这是我想分享的东西。 I assume you are asking this. 我想你是在问这个。

In SQL, imagine something like this (not really syntax): 在SQL中,想象一下这样的事情(不是真正的语法):

begin transaction
insert into table X y= 1, z =2
insert into table A b =1, c =2
commit

Now, imagine there is no column b in table A so this transaction would not work. 现在,假设表A中没有列b,那么此事务将无法进行。

To do same in ASP.Net where you have close to no control over actual DB transactions, combination of try/catch and transaction is what I will suggest. 要在ASP.Net中做同样的事情,而您几乎无法控制实际的数据库事务,那么我会建议将try / catch和transaction结合起来。 Not because it is the right way but just because it can do what you want. 不是因为这是正确的方法,而是因为它可以完成您想要的事情。

Again, this is not the right way. 同样,这不是正确的方法。 Tell more about your problem and more people can help. 详细介绍您的问题,更多的人可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM