標籤:添加 執行sql ack protected source prot ndt label sqlt
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.SQLEXPRESS;database=aaaa;uid=sa;pwd=jcx");
con.Open();
SqlTransaction tran = con.BeginTransaction();//先執行個體SqlTransaction類,使用這個事務使用的是con 這個串連,使用BeginTransaction這個方法來開始執行這個事務
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = tran;
try
{
//在try{} 塊裡執行sqlcommand命令,
cmd.CommandText = "update bb set moneys=moneys-‘" + Convert.ToInt32(TextBox1.Text) + "‘ where ID=‘1‘";
cmd.ExecuteNonQuery();
cmd.CommandText = "update bb set moneys=moneys+‘ aa ‘ where ID=‘2‘";
cmd.ExecuteNonQuery();
tran.Commit();//如果兩個sql命令都執行成功,則執行commit這個方法,執行這些操作
Label1.Text = "添加成功";
}
catch
{
Label1.Text = "添加失敗";
tran.Rollback();//如何執行不成功,發生異常,則執行rollback方法,復原到事務操作開始之前;
}
}
ADO.net 添加事務