.net中的事务

private void btnTransfer_Click(object sender, System.EventArgs e)
{
lblAccount1.Text=" ";
lblAccount2.Text=" ";
int CurrBalance; 
string strSQL = "Select Balance FROM Account where AccNo='"+txtFrom.Text+"'" ;
  
SqlConnection objSqlConnection = new SqlConnection("server=VIJAYK;uid=sa;pwd=playware;database=Account");
objSqlConnection.Open();
SqlDataReader objReader;
SqlCommand objSqlCommand = new SqlCommand(strSQL,objSqlConnection);
SqlTransaction objSqlTransaction =objSqlConnection.BeginTransaction();
objSqlCommand.Transaction=objSqlTransaction;
try
{
objReader = objSqlCommand.ExecuteReader();
objReader.Read();
CurrBalance = Convert.ToInt32(objReader.GetValue(0));
objReader.Close();
if (CurrBalance < Convert.ToInt32(txtAmount.Text))
{
throw(new Exception("转帐金额不足"));
}
strSQL = "Update Account set Balance = Balance - " + txtAmount.Text + " where AccNo = '" + Convert.ToInt32(txtFrom.Text) + "'";
objSqlCommand.CommandText=strSQL;
objSqlCommand.ExecuteNonQuery();  

lblAccount1.Text="帐户 " + txtFrom.Text +" 成功记入借方";
strSQL = "Update Account set Balance =  Balance + "+ txtAmount.Text + " where AccNo = '" + Convert.ToInt32(txtTo.Text) + "'";
objSqlCommand.CommandText = strSQL;
objSqlCommand.ExecuteNonQuery();
lblAccount2.Text="帐户 " + txtTo.Text +" 成功记入贷方";
objSqlTransaction.Commit();
lblException.Text = "成功将金额 " + txtAmount.Text + " 从帐户 " + txtFrom.Text + " 转帐到帐户 " + txtTo.Text + " 。";;
}
catch(Exception ex)
{
objSqlTransaction.Rollback();
lblException.Text = "错误:" + ex.Message;
}
finally
{
objSqlConnection.Close();
}

}
posted @ 2008-11-09 21:43  Edward Xie  阅读(135)  评论(0编辑  收藏  举报