zoukankan      html  css  js  c++  java
  • .Net和SqlServer的事务处理实例

    1,SqlServer存储过程的事务处理
    一种比较通用的出错处理的模式大概如下:
    Create procdure prInsertProducts
    (
     @intProductId int,
     @chvProductName varchar(30),
     @intProductCount int
    )
    AS
    Declare @intErrorCode int
    Select @intErrorCode=@@Error
    Begin transaction
     if @intErrorCode=0
       begin
         -insert products
         insert products(ProductID,ProductName,ProductCount)
         values(@intProductId,@chvProductName,@intProductCount)
         Select @intErrorCode=@@Error --每执行完一条t-sql语句马上进行检测,并把错误号保存到局部变量中
       end
     if @intErrorCode=0
       begin
         -update products
         update products set ProductName='MicroComputer' where ProductID=5
         Select @intErrorCode=@@Error
       end
    if @intErrorCode=0
       commit transaction
    else
       rollback transaction

     Return @intErrorCode --最好返回错误代号给调用的存储过程或应用程序

    2,.Net中使用事务处理
    SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
    myConnection.Open();

    SqlTransaction myTrans = myConnection.BeginTransaction(); //使用New新生成一个事务
    SqlCommand myCommand = new SqlCommand();
    myCommand.Transaction = myTrans;

    try
    {
    myCommand.CommandText = "Update Address set location='23 rain street' where userid='0001'";
    myCommand.ExecuteNonQuery();
    myTrans.Commit();
    Console.WriteLine("Record is udated.");
    }
    catch(Exception e)
    {
    myTrans.Rollback();
    Console.WriteLine(e.ToString());
    Console.WriteLine("Sorry, Record can not be updated.");
    }
    finally
    {
    myConnection.Close();
    }


    说明:在SqlServer中,每条Sql语句都作为一个事务来执行,所以无论在存储过程,还是在.net代码中使用,执行单条Sql语句没有必要使用事务处理,上面只是为了简化表达而对单条Sql语句使用事务处理

  • 相关阅读:
    梦断代码阅读笔记02
    第三周
    第二周
    《大道至简》阅读笔记
    暑假第一周
    hdu-1237简单计算器(栈的运用)
    玩骰子(概率,暴力)
    hdu-5568SUM (dp)
    codeforce-600C. Make Palindrome(贪心)
    codeforce-601A. The Two Routes(最短路)
  • 原文地址:https://www.cnblogs.com/kwklover/p/17810.html
Copyright © 2011-2022 走看看