|
发表于 2020-1-5 14:24:01
|
显示全部楼层
//建立一个连接
SqlConnection con = new SqlConnection("server=.;database=student;uid=sa;pwd=0421");
//定义一个事务
SqlTransaction transaction = null;
try
{
//打开数据库连接
con.Open();
//启动事务
transaction = con.BeginTransaction();
//插入命令
SqlCommand cmd1 = new SqlCommand("insert into student values('111','liujia')", con);
SqlCommand cmd2 = new SqlCommand("insert into class values('111','liujia')", con);
//执行
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
//其他操作,比如说更新
//........
//所有操作完成,提交
transaction.Commit();
}
catch (Exception ex)
{
//先回滚
transaction.Rollback();
//下面进行异常处理
//...
}
finally
{
//关闭数据库连接
con.Close();
}
}
|
|