读书人

数据库事务回滚,该怎么处理

发布时间: 2012-03-28 15:40:03 作者: rapoo

数据库,事务回滚
同时向几个表插入数据,SQL语句是
INSERT INTO aaa...
INSERT INTO bbb...
...

try
{
//接受影响行数
com.ExecuteNonQuery();
//提交事务
tran.Commit();
}
catch (Exception ex)
{
//出现异常 即回滚事务 防止出现脏数据
tran.Rollback();
Response.Write(ex.Message);
break;
}

如果第一句,INSERT INTO aaa...成功了,第二句INSERT INTO bbb...出现异常,tran.Rollback();能让第一句insert 插入的数据也消失吗?

[解决办法]

C# code
public void ExecuteTransaction(string connectionString){    using (OleDbConnection connection =               new OleDbConnection(connectionString))    {        OleDbCommand command = new OleDbCommand();        OleDbTransaction transaction = null;        // Set the Connection to the new OleDbConnection.        command.Connection = connection;        // Open the connection and execute the transaction.        try        {            connection.Open();            // Start a local transaction            transaction = connection.BeginTransaction();            // Assign transaction object for a pending local transaction.            command.Connection = connection;            command.Transaction = transaction;            // Execute the commands.            command.CommandText =                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";            command.ExecuteNonQuery();            command.CommandText =                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";            command.ExecuteNonQuery();            // Commit the transaction.            transaction.Commit();            Console.WriteLine("Both records are written to database.");        }        catch (Exception ex)        {            Console.WriteLine(ex.Message);            try            {                // Attempt to roll back the transaction.                transaction.Rollback();            }            catch            {                // Do nothing here; transaction is not active.            }        }        // The connection is automatically closed when the        // code exits the using block.    }}
[解决办法]
也可以使用存储过程.
[解决办法]
可以的,只要在同一个事务下任何操作失败都会使所有操作回滚
[解决办法]
探讨
可以的,只要在同一个事务下任何操作失败都会使所有操作回滚

[解决办法]
当然可以,都写在一个事务里

C# code
SqlTransaction trans = new SqlTransaction();SqlCommand cmd = new SqlCommand("insert into aaa...", conn);                        cmd.Transaction = trans;
[解决办法]
可以的
[解决办法]
没问题
[解决办法]
探讨

可以的,只要在同一个事务下任何操作失败都会使所有操作回滚

[解决办法]
不能回滚它叫事务干嘛
你可以了解一些内部机制就知道它是怎么具体实现了
[解决办法]
嗯,写在同一个事务里, 如果有一条失败,就全部回滚了, 这个用存储过程来操作比较好些
------解决方案--------------------


不管你有多少操作。失败了,回滚。都会返回到以前的状态!

读书人网 >asp.net

热点推荐