事务的使用
获取连接对象:
引用:using System.Configuration;
string connStr = ConfigurationManager.ConnectionStrings["conStr"].ToString();
写法一:
using (SqlConnection conn = new SqlConnection (connStr)
{
conn.Open();
using (SqlTransaction tran = conn.BeginTransaction())
{
using (SqlCommand cmd = conn.CreateCommand())
{
try
{
cmd.Transaction = tran; //为命令指定事务
cmd.CommandText = "insert into info values('小谢','男')";
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into info values('小周','男')";
cmd.ExecuteNonQuery();
tran.Commit(); //事务提交
}
catch (Exception)
{
tran.Rollback(); //事务回滚
}
}
}
}
写法二:
SqlConnection conn = new SqlConnection(连接对象);
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = tran;
try
{
cmd.CommandText = "insert into info values('小谢','男')";
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into info values('小周','男')";
cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception)
{
tran.Rollback();
}
conn.Close();
多条sql语句:
List<string> sqlStr = new List<string>();
string sql1 = "insert into info values('小吴','男')";
string sql2 = "insert into info values('小胡','男')";
sqlStr.Add(sql1);
sqlStr.Add(sql2);
using (SqlConnection conn = new SqlConnection (connStr))
{
conn.Open();
using (SqlTransaction tran = conn.BeginTransaction())
{
using (SqlCommand cmd = conn.CreateCommand())
{
try
{
cmd.Transaction = tran; //为命令指定事务
foreach (var item in sqlStr)
{
cmd.CommandText = item;
cmd.ExecuteNonQuery();
}
tran.Commit();
}
catch (Exception)
{
tran.Rollback(); //事务回滚
}
}
}
conn.Close();
}