SoFunction
Updated on 2025-03-07

C# Execution SQL transaction usage example

using System; 
using ; 
using ; 
using ; 
using ; 
using ; 
using ; 
using ; 
 
namespace user activation

    public partial class WebForm3 :  
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
 
        } 
 
        protected void Button1_Click(object sender, EventArgs e) 
        { 
            string connStr=["ConnStr"].ConnectionString; 
            using(SqlConnection conn=new SqlConnection(connStr)) 
            { 
                (); 
using (SqlTransaction tran = ()) //Start database transaction. That is, create a transaction object tran
                { 
                    using (SqlCommand cmd =new SqlCommand()) 
                    { 
                        = conn; 
= tran; //Get or set the transaction to which it is to be executed
                        try 
                        { 
//Execute the sqlconnection command in the try{} block
                            = "update bb set Moneys=Moneys-" + + " where ID=" + ; 
                            (); 
                            = "update bb set Moneys=Moneys+" + + " where ID=" + ; 
                            (); 
 
(); //If both SQL commands are executed successfully, execute the commit method to perform these operations.
 
= "Successful transfer";
                        } 
                        catch 
                        { 
= "Transfer failed";
();//If the execution is unsuccessful and an exception is sent, the rollback method is executed and the transaction operation is rolled back before the start of the transaction operation.
                        } 
                    } 
                } 
            } 
        } 
    } 
}