您的位置:首页 > 其它

ADO.NET--事务的通用数据访问方法

2017-09-04 02:59 435 查看

事务—-通用访问类



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Demo
{
class SQLHelper
{
private static  string connString = "Server=.;DataBase=StudentManager;Uid=sa;Pwd=aaa999a9";
public static int UpdateByTran(List<string>sqlList)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
try
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();//开启事务
int result = 0;
foreach (string sql in sqlList)
{
cmd.CommandText = sql;
result += cmd.ExecuteNonQuery();//执行查询
}
cmd.Transaction.Commit();//提交事务
return result;
}
catch (Exception ex)
{
if (cmd.Transaction != null)
cmd.Transaction.Rollback();//回滚事务
throw new Exception("调用事务更新方法时出现异常:" + ex.Message);
}
finally
{
if (cmd.Transaction != null)
cmd.Transaction = null; //清除事务
conn.Close();
}
}

}
}


测试ADO.Net事务回滚





查看数据库返回



一样的错误信息。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
class Program
{
static void Main(string[] args)
{
List<string> sqlList = new List<string>()
{
"delete from Students where StudentId=100010",
"delete from Students where StudentId=100013",//有外键约束
"delete from Students where StudentId=100014",
"delete from Students where StudentId=100011"
};
string sql = "Select Count(*) from Students";
Console.WriteLine("删除学员总数前:{0}",SQLHelper.GetSingleResult(sql).ToString());
Console.WriteLine("******************************************************");
int result = 0;
try
{
result = SQLHelper.UpdateByTran(sqlList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("*******************************");
}
if (result > 0)
Console.WriteLine("删除成功");
else
Console.WriteLine("删除失败");
Console.WriteLine("*****************************************************");
Console.WriteLine("删除后学员总数:{0}",SQLHelper.GetSingleResult(sql).ToString());
Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  事务 数据