C#代码中的事务

private void button1_Click(object sender, EventArgs e)
        {

            // 显示事务

            SqlTransaction tran;

            string sConn = "server=.\\DS;database=T105_2005;uid=sa;pwd=sasa";
            string sql1 = "update zh set zm=zm-"+Convert.ToDouble(this.textBox1.Text.Trim())+" where zid='1002'";
            string sql2 = "update zh set zm=zm+" + Convert.ToDouble(this.textBox1.Text.Trim()) + " where zid='1001'";

            SqlConnection con = new SqlConnection(sConn);
            con.Open();
            tran = con.BeginTransaction();
            SqlCommand com = new SqlCommand();
            try
            {

                com.Connection = con;
                com.Transaction = tran;

 


             
                com.CommandText = sql1;
                com.ExecuteNonQuery();
                com.CommandText = sql2;
                com.ExecuteNonQuery();
                con.Close();

                MessageBox.Show("帐装成功");
                tran.Commit();
            }
            catch
            {
                MessageBox.Show("帐装失败");
                tran.Rollback();
            }


           
        }
    }

posted @ 2009-07-27 10:29  xumingming  阅读(708)  评论(1编辑  收藏  举报