码迷,mamicode.com
首页 > 其他好文 > 详细

c#事务

时间:2014-07-24 22:11:52      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:os   io   re   c   cti   ar   new   sql   

 1.正常程序里的事务:

  using (System.Transactions.TransactionScope ts = new TransactionScope())
        {
            try
            {
                //Sql语句
                ts.Complete();//提交事务
            }
            catch (Exception e)
            {
                Logger.WriteLog(e.Message);
            }
            finally
            {
                ts.Dispose();//释放事务
            }
        }
2.sql语句中事务:

public void shiwu(){

try{

  SqlConnection conn = new SqlConnection(SqlHelper.connectionString);
        conn.Open();
        SqlTransaction tran = null;
        tran = conn.BeginTransaction();
        SqlCommand cmd = new SqlCommand();
        cmd.Transaction = tran;//挂起事务
        cmd.Connection = conn;

        sql_insert=sql;//sql语句

        DbHelperSQL.PrepareCommand(cmd, conn, tran, sql_insert, null);
                            int val = cmd.ExecuteNonQuery();

        tran.Commit();//执行成功 事务提交
}

catch(Exception e)

             {

               tran.Rollback();//报错的话 事务回滚

             }

finally
            {
               conn.Close();//关闭连接
            }

}

c#事务,布布扣,bubuko.com

c#事务

标签:os   io   re   c   cti   ar   new   sql   

原文地址:http://www.cnblogs.com/loveailsa10000/p/3866138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!