下面将为您介绍如何执行多条SQL语句,实现数据库事务的方法,供您参考,如果您对SQL语句和事务感兴趣的话,不妨一看,详细对您学习SQL大有帮助。
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(IList<string> 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<string> l = new List<string>();
for (int i = 0; i <this.DataList1.Items.Count; i++) { CheckBox c= (CheckBox)this.DataList1.Items[i].FindControl("CheckBox1");
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);
}
【编辑推荐】