SqlTransaction事务使用示例

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CNTVS.TOOLS;

public partial class _Default : System.Web.UI.Page 
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        SqlConnection conn 
= Database.GetConn();
        SqlTransaction st 
= conn.BeginTransaction();
        
try
        
{
           
            
string sql = "Insert Into T_Test(F_Name) values('A')";            
            Database.ExecuteNonQuery(st, CommandType.Text, sql);

            
//这里会报错,在挂起的事务中,该事务分配的连接,不能再独占使用
            
//string A = Database.ExecuteScalarToStr(conn,CommandType.Text,"Select F_ID From T_Test where F_Name='A'");
            
            sql 
= "Insert Into T_Test2(F_ID,F_Age) values(1,2)";
            Database.ExecuteNonQuery(st, CommandType.Text, sql);
            st.Commit();           
          
        }

        
catch (Exception Ex)
        
{
            st.Rollback();
            Website.WriteError(Ex);
        }

        
finally 
        
{
            Database.Dispose(conn);
        }

    }

}
posted @ 2007-12-26 23:28  菩提树下的杨过  阅读(1533)  评论(0编辑  收藏  举报