日期:2014-05-17  浏览次数:20736 次

在Asp.Net中使用事务
private string mConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();

using (OracleConnection vConn=new OracleConnection(mConnStr))

        {

            vConn.Open();

            OracleTransaction vTrans = vConn.BeginTransaction();

            try

            {

                OracleCommand vCmd = vConn.CreateCommand();

                vCmd.Transaction = vTrans;

                string[] vSqlList = {“insert into X1(workno,name,sex) values(‘22′,’2′,’22′)”,”insert into x2(workno,subject,score) values(‘333′,’33′,’33′)” };

                foreach (string vSql in vSqlList)

                {

                    vCmd.CommandText = vSql;

                    vCmd.ExecuteNonQuery();

                }

                vTrans.Commit();

            }

            catch (Exception ex)

            {

                vTrans.Rollback();

                throw ex;

            }

        }

  SqlConnection conn = new SqlConnection(connString);
  conn.Open();
  SqlTransaction tran = conn.BeginTransaction(); //创建事务Transaction

  string strSQL = “INSERT INTO Employees(FirstName, LastName, City, Address) values (@paramFirstName,@paramLastName,@paramCity,@paramAddress)”;
  SqlCommand cmd = new SqlCommand(strSQL, conn,tran);  //创建SqlCommand

  try
  {
   cmd.Parameters.Add(“@paramFirstName”, SqlDbType.NVarChar, 20).Value = txtFirstName.Text;
   cmd.Parameters.Add(“@paramLastName”, SqlDbType.NVarChar, 10).Value = txtLastName.Text;
   cmd.Parameters.Add(“@paramCity”, SqlDbType.NVarChar, 15).Value = txtCity.Text;
   cmd.Parameters.Add(“@paramAddress”, SqlDbType.NVarChar, 60).Value = txtAddress.Text;
   cmd.ExecuteNonQuery();
   tran.Commit();  //确认事务
            txtMsg.Text = “新增数据成功,事务确认!”;
  }
  catch
  {
   tran.Rollback();   //事务回滚
            txtMsg.Text = “新增数据失败,事务Rollback!”;
  }

  finally
  {
   conn.Close();
   conn.Dispose();
   tran.Dispose();
   cmd.Dispose();
  }