执行多条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);
    }

 

posted @ 2010-07-20 17:48  冰翼  阅读(177)  评论(0)    收藏  举报