2013-11-27 99 views
0

我正在做一個在asp.net中的Web應用程序。 我有一個類CommonDB保存數據。在asp.net中的交易管理

public class CommonDB 
{ 

    private static string GetConnectionString = ConfigurationManager.ConnectionStrings["Db"].ToString(); 


    public static SqlConnection GetConnection() 
    { 
     SqlConnection Con = new SqlConnection(GetConnectionString); 
     if (Con.State == ConnectionState.Open) 
     { 
      Con.Close(); 
     } 
     return Con; 
    } 

    public static int ExecuteNonquery(SqlCommand cmd) 
    { 
     SqlConnection Con = GetConnection(); 

     Con.Open(); 

     try 
     { 
      cmd.Connection = Con;    
      Con.Close(); 
      return ReturnVal; 
     } 


     catch 
     {     
      Con.Close(); 
      return 0; 

     } 


    } 

} }

我使用下面的函數來保存數據

public int AddGroupMaster() //Inserting 
    { 
     try 
     {     
      SqlCommand cmd = new SqlCommand(); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.CommandText = "NV_Group_Master_Add"; 
      cmd.Parameters.AddWithValue("@Group_ID", iGroupId); 
      cmd.Parameters.AddWithValue("@Group_Code", strGroupName); 
      cmd.Parameters.AddWithValue("@Group_Name", strGroupName); 
      cmd.Parameters.AddWithValue("@Created_On", strCreatedOn); 
      cmd.Parameters.AddWithValue("@Modified_On", strModifiedOn); 
      iReturn = CommonDB.ExecuteNonquery(cmd); 
      return iReturn; 
     } 

     catch { return 0; } 
    } 

此功能從代碼中調用後面,如:

protected void btnSave_Click(object sender, EventArgs e) 
    { 
     try 
     { 

      objGroup.strGroupName = txtGroupName.Text.Trim(); 
      objGroup.strCreatedOn = DateTime.Today.ToString(); 
      objGroup.strModifiedOn = ""; 
      objGroup.AddGroupMaster(); 

     } 

     catch 
     { 

     } 

    } 

我想用提交和回滾。在我的編碼中如何可能? 請建議解決方案

+0

這是asp.net,不是Classic asp – John

回答

0

在您的方案中,您必須在您的CommonDB庫中執行此操作。

例如,您ExecuteNonQuery方法是這樣的:

public static int ExecuteNonquery(SqlCommand cmd) { 

    int retVal; 
    SqlConnection Con = GetConnection(); 
    DbTransaction tran; 

    try { 
     cmd.Connection = Con; 
     cmd.Connection.Open(); 
     tran = cmd.Connection.BeginTransaction; 
     cmd.Transaction = tran; 
     retVal = cmd.ExecuteNonQuery; 
     tran.Commit() 
    } catch { 
     tran.Rollback(); 
     throw; 
    } finally { 
     cmd.Connection.Close() 
    } 

    return retVal; 
} 

是的,不要忘記讓一個參考System.Data.Common