使用存储过程操作数据,使用c#进行事务

时间:2014-03-26 05:27:04

标签: c# sql-server stored-procedures

我在3个不同的表上有3个存储过程..其主要目的是插入,删除,查看和更新​​。

我有一个注册表单,其中包含需要由用户填写的9个字段。一旦用户点击提交,前3个字段数据将被发送到第一个SP,接下来的3个到第二个SP,以及最后3个到第三个SP。

我希望实现事务来实现它......这样如果所有数据都成功添加,那么它的提交或整个数据应该回滚。

string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd1 = new SqlCommand(con, CommandType.StoredProcedure, "usp_additemdata",      p);
SqlCommand cmd2 = new SqlCommand(con, CommandType.StoredProcedure, "usp_addpricedata", p)
SqlTransaction tran = null;
try
{

con.Open();

cmd1.Transaction = tran;
cmd2.Transaction = tran;

cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
Commit the transaction.
tran.Commit();
 }
catch
{

 tran.Rollback();
}
finally
{
con.Close();
}

2 个答案:

答案 0 :(得分:0)

您可以在此使用Transaction Scope

using (TransactionScope scope = new TransactionScope())
    {
        using (SqlConnection connection1 = new SqlConnection(yourconnectionstring))
        {
           //your commands here
        }

        // The Complete method commits the transaction. If an exception has been thrown,
        // Complete is not  called and the transaction is rolled back.
        scope.Complete();
    }

答案 1 :(得分:0)

SqlConnection db = new SqlConnection("ConnectionStringHere");
      SqlTransaction transaction;

  db.Open();
  transaction = db.BeginTransaction();
  try 
  {
    var SqlC1= new SqlCommand("SP1", db, transaction);
    <Add parameters in SqlC1>
        SqlC1.ExecuteNonQuery();
    var SqlC2= new SqlCommand("SP2", db, transaction);
    <Add parameters in SqlC2>
        SqlC2.ExecuteNonQuery();

     var SqlC3= new SqlCommand("SP3", db, transaction);
    <Add parameters in SqlC3>
        SqlC3.ExecuteNonQuery();
     transaction.Commit();
  } 
  catch (SqlException sqlError) 
  {
     transaction.Rollback();
  }
  db.Close();**strong text**