Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/9 1:34:54 ADO.NET使用事务的使用实例
ADO.NET使用事务的使用实例
使用事务事务是作为单个逻辑工作单元执行的一系列操作。一个逻辑工作单元必须有4个属性,称为 ACID(原子性、一致性、隔离性和持久性)属性,只有这样才能成为一个事务。事务管理特性,强制保持事务的原子性和一致性。事务启动之后,就必须成功完成,否则SQL Server将撤消该事务启动之后对数据所作的所有修改。下面将应用事务的一致性来排除程序在运行过程中可能发生的一系列“危险”因素,确保数据的安全,例如,一个用户在取钱时,卡已放入取款机进行操作,等待取款,这时突然停电,通过事务可以帮助用户挽回损失,将信息恢复到操作之前的状态。程序运行结果如图1、图2和图3所示。图1 查询窗体图2 提示窗体图3 提示窗体程序开发步骤如下。(1)新建一个windows窗体(FrmTran),在窗体上添加相应的控件(如图1所示)。(2)主要程序代码如下。首先实例化一个连接对象connection,其次通过连接对象connection又分别实例化一个Sql Transaction对象sqlTran、一个SqlCommand对象command,然后再将command对象的Transaction属性与sqlTran对象关联起来,通过事物实现程序的一致性,程序代码如下。public bool Tran(string strID,string strName,string strSex,string strDelID,bool IfDO){using (SqlConnection connection = ConDB()); //创建连接对象{SqlTransaction sqlTran = connection.BeginTransaction();//开始事务SqlCommandcommand = connection.CreateCommand();//创建SqlCommand对象command.Transaction = sqlTran;//将SqlCommand与SqlTransaction关联起来try{command.CommandText = "insert into t_people values('" + strID + "','" + strName +"','" + strSex + "')";command.ExecuteNonQuery();command.CommandText = "delete from t_people where tb_PID='" + strDelID + "'";command.ExecuteNonQuery();if (IfDO)//抛出异常,令其发生回滚{throw new Exception();}sqlTran.Commit();connection.Close();return True;}catch (Exception ex){Console.WriteLine(ex.Message);sqlTran.Rollback();return False;}}}为Tran方法获取参数,如果Tran方法成功,则信息成功添加,否则添加失败。为了使读者可以更好地了解事务的工作原理,程序中人为的标识事务的操作方式(提交、回滚)。程序代码如下:private void button1_Click(object sender, EventArgs e){ClsDB.ClsDBControl DBDT = new OptDB.ClsDB.ClsDBControl();string strid, strname, strsex, strDelid;strid = this.textBox1.Text.Trim().ToString();strname = this.textBox2.Text.Trim().ToString();strsex = this.textBox3.Text.Trim().ToString();strDelid = this.textBox4.Text.Trim().ToString();bool Bt;if (this.radioButton1.Checked){Bt = False;}else{Bt = True;}if (DBDT.Tran(strid, strname, strsex, strDelid, Bt)){MessageBox.Show("事务供交成功");}else{MessageBox.Show("事务回滚成功");}}完整程序代码如下:★ ★★★★FrmTran.cs窗体代码文件完整程序代码★★★★★using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace OptDB{public partial class FrmTran : Form{public FrmTran(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){ClsDB.ClsDBControl DBDT = new OptDB.ClsDB.ClsDBControl();string strid, strname, strsex, strDelid;strid = this.textBox1.Text.Trim().ToString();strname = this.textBox2.Text.Trim().ToString();strsex = this.textBox3.Text.Trim().ToString();strDelid = this.textBox4.Text.Trim().ToString();bool Bt;
赞