SqlTransaction在c#中是怎么使用的
展开全部
SqlTransaction 是事务,下面给你一个例子
private static void ExecuteSqlTransaction(string connstr)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
SqlTransaction transaction = conn.BeginTransaction("SampleTransaction"); //开始事务
cmd.Connection = conn;
cmd.Transaction = transaction;
try
{
cmd.CommandText =
"Insert into Department (ID, Name) VALUES (2, '开发部')";
cmd.ExecuteNonQuery();
cmd.CommandText =
"Insert into Users(ID, Name,DepartmentID) VALUES (2, 'sxw',2)";
cmd.ExecuteNonQuery();
transaction.Commit(); //事务完成之后提交事务
}
catch (Exception ex)
{
transaction.Rollback(); //如果事务没有完成,就回滚事务
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询