C# 执行SQL事务实例代码

public void RunSqlTransaction(string myConnString) 
{
    SqlConnection myConnection 
= new SqlConnection(myConnString);
    myConnection.Open();

    SqlCommand myCommand 
= myConnection.CreateCommand();
    SqlTransaction myTrans;

    
// Start a local transaction
    myTrans = myConnection.BeginTransaction();
    
// Must assign both transaction object and connection
    
// to Command object for a pending local transaction
    myCommand.Connection = myConnection;
    myCommand.Transaction 
= myTrans;

    
try
    {
      myCommand.CommandText 
= "Insert into Region (RegionID, RegionDescription) VALUES (100, ´Description´)";
      myCommand.ExecuteNonQuery();
      myCommand.CommandText 
= "Insert into Region (RegionID, RegionDescription) VALUES (101, ´Description´)";
      myCommand.ExecuteNonQuery();
      myTrans.Commit();
      Console.WriteLine(
"Both records are written to database.");
    }
    
catch(Exception e)
    {
      
try
      {
        myTrans.Rollback();
      }
      
catch (SqlException ex)
      {
        
if (myTrans.Connection != null)
        {
          Console.WriteLine(
"An exception of type " + ex.GetType() +
                            
" was encountered while attempting to roll back the transaction.");
        }
      }
    
      Console.WriteLine(
"An exception of type " + e.GetType() +
                        
" was encountered while inserting the data.");
      Console.WriteLine(
"Neither record was written to database.");
    }
    
finally 
    {
      myConnection.Close();
    }



 

相关文章:

  • 2022-03-06
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-09-30
  • 2021-12-27
  • 2021-08-05
猜你喜欢
  • 2021-12-18
  • 2022-03-01
  • 2021-12-18
  • 2021-04-20
  • 2021-08-16
  • 2021-09-01
相关资源
相似解决方案