using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string str = @"Data Source=G35;Initial Catalog=SSMS;Integrated Security=True";
SqlConnection sqlconn = new SqlConnection(str);
SqlTransaction tran;//定义事务
sqlconn.Open();
tran = sqlconn.BeginTransaction();//事务开始
try
{
SqlCommand comm2 = new SqlCommand("update student_tb set stu_name='中才' where stu_id=1");
comm2.Connection = sqlconn;
comm2.Transaction = tran;
comm2.ExecuteNonQuery();
SqlCommand comm = new SqlCommand("delete from student_tb where stu_id");
comm.Connection = sqlconn;
comm.Transaction = tran;
comm.ExecuteNonQuery();
tran.Commit();//事务提交
}
catch (Exception ex)
{
tran.Rollback();//回滚
MessageBox.Show(ex.ToString());
}
finally
{
sqlconn.Close();
}
}
}
}
C# 事务的调用和回滚
最新推荐文章于 2021-01-26 18:20:29 发布