ASP.NET Tutorial/ADO.net Database/Transaction

Материал из .Net Framework эксперт
Версия от 11:56, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Execute database commands within a single local transaction. You can test rollback and partial rollback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Begin Local Transactions</title>
</head>
<body>
    <div id="pageContent">    
        <form id="form1" runat="server">
          <h2>Click this button to display current data.</h2>
        <asp:Button id="ShowButton" runat="server" Text="Show Data" OnClick="ShowButton_Click"></asp:Button>
        
        <h2>Click this button to execute a transaction</h2>
        <asp:Button id="ExecuteButton" runat="server" Text="Execute Transaction" OnClick="ExecuteButton_Click"></asp:Button>
        <asp:CheckBox id="CheckBox_Partial" runat="server" Text="Partial Rollback"></asp:CheckBox>
        <h2>Click this button to restore the original state of data</h2>
        <asp:Button id="RestoreButton" runat="server" Text="Restore" OnClick="RestoreButton_Click"></asp:Button>
        <hr>
        <asp:Label runat="server" id="lblMessage" /> 
        <br>
        <asp:DataGrid id="grid" runat="server" visible="False" CellPadding="4" GridLines="None" ForeColor="#333333" CssClass="shadowed" font-size="X-Small" font-names="verdana">
          <AlternatingItemStyle BackColor="White" />
          <ItemStyle BackColor="#EFF3FB" />
          <HeaderStyle ForeColor="White" BackColor="#507CD1" Font-Bold="True" />
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <EditItemStyle BackColor="#2461BF" />
                <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        </asp:DataGrid>
        </form>
    </div>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
    private const string ConnString = "SERVER=(local);DATABASE=northwind;Trusted_Connection=yes;";
    private const string SelectCmd = "SELECT employeeid, firstname, lastname FROM Employees";
    private const string UpdateCmd = "UPDATE Employees SET firstname="Michela" WHERE EmployeeID=1";
    private const string InsertCmd = "INSERT INTO Employees (firstname,lastname) VALUES ("Dino", "Esposito")";
    protected void ShowButton_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.rumandText = SelectCmd;
            conn.Open();
            grid.DataSource = cmd.ExecuteReader();
            grid.DataBind();
            grid.Visible = true;
            conn.Close();
        }
    }
    protected void ExecuteButton_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            SqlTransaction t = conn.BeginTransaction();
            cmd.Transaction = t;
            try
            {
                cmd.rumandText = UpdateCmd;
                cmd.ExecuteNonQuery();
                t.Save("AfterUpdate");
                cmd.rumandText = InsertCmd;
                cmd.ExecuteNonQuery();
                if (CheckBox_Partial.Checked)
                    t.Rollback("AfterUpdate");
                t.rumit();
                lblMessage.Text = "<b>Done</b>";
                grid.Visible = false;
            }
            catch (Exception exc)
            {
                t.Rollback();
                lblMessage.Text = "<b>Error occurred: </b>" + exc.Message;
            }
        }
    }
    protected void RestoreButton_Click(object sender, EventArgs e) {
        using (SqlConnection conn = new SqlConnection(ConnString)) {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            SqlTransaction t = conn.BeginTransaction();
            cmd.Transaction = t;
            try {
                cmd.rumandText = "UPDATE Employees SET firstname="Nancy" WHERE EmployeeID=1";
                cmd.ExecuteNonQuery();
                cmd.rumandText = "DELETE FROM Employees WHERE EmployeeID >9";
                cmd.ExecuteNonQuery();
                t.rumit();
                lblMessage.Text = "<b>Done</b>";
                grid.Visible = false;
            }
            catch (Exception exc)
            {
                t.Rollback();
                lblMessage.Text = "<b>Error occurred: </b>" + exc.Message;
            }
        }
    }
}


Use transaction to group operations (VB.net)

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
   "declare connection
   dim Conn as new OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
   sub Page_Load(Sender as Object, e as EventArgs)
      dim objTrans as OleDbTransaction
      dim objCmd as OleDbCommand = new OleDbCommand _
         ("DELETE from employee where UserID = 32", Conn)
      Conn.Open()
      objTrans = Conn.BeginTransaction()
      objCmd.Transaction = objTrans
          try
         objCmd.rumandText = "INSERT INTO employee " & _
            "(ID, FirstName, LastName) VALUES " & _
            "(109, "J", "S")"
         objCmd.ExecuteNonQuery()
         objCmd.rumandText = "INSERT INTO employee " & _
            "(ID, FirstName, LastName) VALUES " & _
            "(119, "J", "S")"
         objCmd.ExecuteNonQuery()
         objTrans.rumit()
             Label1.Text = "Both operations performed successfully"
      catch ex as OleDbException
         objTrans.RollBack()
         Label1.Text = ex.Message & ""
         Label1.Text = "Both operations failed"
      finally
         objCmd.Connection.Close()
      end try
   end sub
</script>
<html><body>
   <form runat="server">
      <asp:Label id="Label1" runat="server"
         maintainstate=false /><br>
   </form>
</body></html>