现在的位置: 首页 > 数据库 > 正文

SQL事务处理

2017年12月07日 数据库 ⁄ 共 1100字 ⁄ 字号 评论关闭

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace WebDemo
{
    public partial class Affairs : System.Web.UI.Page
    {
        public string sqlconn = System.Configuration.ConfigurationManager.ConnectionStrings["SQLCONN"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(sqlconn);
            SqlCommand cmd = new SqlCommand();
            SqlTransaction Transaction=null;
            try
            {
                //打开数据库连接
                   conn.Open();
                //开启事务
                   Transaction = conn.BeginTransaction();
                cmd.Transaction = Transaction;
                cmd.Connection = conn;
                string sql = "insert into Students values('杨飞宰','男','N2d08007')";
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery(); 
                string sql2 = "insert into Stud_Subjects values('C#','98','1')";
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql2;
                cmd.ExecuteNonQuery();
                //提交事务
                  Transaction.Commit();
                Response.Write("添加成功!");
            }
            catch
            {
                //事务回滚
                   Transaction.Rollback();
                Response.Write("添加失败!");
            }
            finally
            {
               //释放事务
                  Transaction.Dispose();
               //关闭数据库连接
                  conn.Close();
            }
        }
    }
}

 

抱歉!评论已关闭.