zoukankan      html  css  js  c++  java
  • 个人学习代码保存:例4.在.net程序中使用事务处理

    此实例无任何控件,固只有后台代码:Default.aspx.cs
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;

    public partial class _Default : System.Web.UI.Page 
    {
        
    protected void Page_Load(object sender, EventArgs e)
        
    {
            
    if (!IsPostBack)
            
    {
                
    string connstr=ConfigurationManager.AppSettings["ConnectionString"].ToString();
                SqlConnection con1 
    = new SqlConnection(connstr);
                
    if (con1.State.Equals(ConnectionState.Closed))
                
    {
                    con1.Open();
                }

                
    string sql1 = "insert into guestbook(title,body) values('事务添加1','事务添加1')";
                SqlCommand cmd1 
    = new SqlCommand(sql1,con1);

                
    //事务开始 当使用con1.BeginTransaction()后,那么每一个con1相关联的command命令都应该使用这个事务 因而当我们用cmd2时需要新创建一个con2
                SqlTransaction myTran = con1.BeginTransaction();
                cmd1.Transaction 
    = myTran;

                
    try
                
    {
                    cmd1.ExecuteNonQuery();

                    
    string sql2 = "insert into guestbook(title,body) values('事务添加2','事务添加2')";
                    SqlConnection con2 
    = new SqlConnection(connstr);
                    
    if (con2.State.Equals(ConnectionState.Closed))
                    
    {
                        con2.Open();
                    }

                    SqlCommand cmd2 
    = new SqlCommand(sql2, con2);
                    cmd2.ExecuteNonQuery();
                    con2.Close();
                    myTran.Commit();
                    Response.Write(
    "事务执行成功!");
                }

                
    catch
                
    {
                    myTran.Rollback();
                    Response.Write(
    "事务执行失败!");
                }

                
    finally
                
    {
                    con1.Close();
                }

            }


        }

    }

  • 相关阅读:
    careercup-C和C++ 13.6
    C++中名字隐藏,名字查找优先于类型检查
    careercup-C和C++ 13.5
    careercup-C和C++ 13.4
    careercup-C和C++ 13.3
    careercup-C和C++ 13.2
    careercup-C和C++
    careercup-排序和查找 11.7
    RMAN Catalog创建、配置和管理
    Linux一块网卡添加多个IP地址
  • 原文地址:https://www.cnblogs.com/wbcms/p/1036538.html
Copyright © 2011-2022 走看看