asp.net 的事务

来源:互联网 发布:linux需要网卡驱动 编辑:程序博客网 时间:2024/06/07 05:08
private void btnOK_Click(object sender, System.EventArgs e)
{
    SqlConnection myConnection = new SqlConnection("Server=(local);Initial Catalog=Northwind;uid=sa;pwd=sa;");
    myConnection.Open();

    // 启动一个事务
    SqlTransaction myTrans = myConnection.BeginTransaction();

    // 为事务创建一个命令
    SqlCommand myCommand = new SqlCommand();
    myCommand.Connection=myConnection;
    myCommand.Transaction = myTrans;
    try
    {
       myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (110, 'Description')";

       myCommand.ExecuteNonQuery();


       myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (111, 'Description')";

       myCommand.ExecuteNonQuery();


       myTrans.Commit();
       Response.Write("成功写入记录!");
    }
    catch(Exception Ex)
    {
       myTrans.Rollback();
       Response.Write(Ex.ToString());
       Response.Write("写入数据库失败!");
    }
    finally
    {

        myConnection.Close();
    }
}
原创粉丝点击