Sql Server事务简单用法

 var conStr = "server=localhost;database=Data;user=sa;pwd=123456";
using (var connection = new SqlConnection(conStr))
{
connection.Open();
var sql =
string.Format(
"update dbo.AutoStationData set Temperture={0} where StationNum=58365 and DateTime='{1}'", 8.5,
new DateTime(, , , , , , ));//可以正常执行的sql语句 var sql2 = string.Format(
"update dbo.AutoStationData set Temperture={0} where StationNu=98801 and DateTime='{1}'", 8.1,
new DateTime(, , , , , , )); //不可以正常执行的sql语句 不存在字段StationNu
using (var command = new SqlCommand(sql,connection))
{
var transation = connection.BeginTransaction();//创建事务
try
{
command.Transaction = transation; command.CommandText = sql;
command.ExecuteNonQuery(); command.CommandText = sql2;
command.ExecuteNonQuery(); transation.Commit();
}
catch (Exception e1)
{
try
{ transation.Rollback();
}
catch (Exception e2)
{ Console.Write(e2.Message);
} } }
}

写一个可以正常执行的sql语句sql,一个错误的sql语句sql2。执行完21行代码,在数据库中查询全表,会显示正在查询...,直接执行后面的代码,由于sql2不能正确执行,跳转到catch,执行回滚,21行修改的字段值还原。数据库这才能执行全表查询 正在查询....变成查询已成功执行。从执行第一个sql语句开始,知道提交事务成功,或者回滚成功这段时间这个事务独占这一张表,也体现了事务的原子性。

上一篇:Atitit. C# java 的api 目录封装结构映射总结


下一篇:Hangfire实战(一)------Hangfire+SQL Server实现简单的任务调度