下面将为您介绍如何执行多条SQL语句,实现数据库事务的方法,供您参考,如果您对SQL语句和事务感兴趣的话,不妨一看,详细对您学习SQL大有帮助 。
///
/// 执行多条SQL语句,实现数据库事务 。
///
/// 多条SQL语句
public static void ExecuteSqlTran(IList SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
string upsql = "update 表 set=123 where id=";//省略其他SET
IList l = new List();
for (int i = 0; i
TextBox tb = (TextBox)this.DataList1.Items[i].FindControl("TextBox1");
//下面几个TextBox省略
if(c.Checked)
{
l.Add("update 表 set="+tb.Text+" where id="+ this.DataList1.DataKeys[i].ToString());
}
}
SqlServerHelper.ExecuteSqlTran(l);
}
【编辑推荐】
存储过程优化的SQL语句写法
使用存储过程检查引起死锁的SQL语句及进程
SQL语句中CASE WHEN的使用实例
巧用GO将多次重复执行SQL语句
父子分类关系查询使用的SQL语句介绍