2

public bool AddEntity(int parentId,string description) { try { _connection.Open(); SqlCommand command = new SqlCommand(「INSERT Structure(Path,Description)」+ 「VALUES(」+ GetPath(parentId)+「.GetDescendant(」+ GetLastChildPath(parentId,1)+「,NULL),」+ description +「)」,_connection);異常處理 - 有沒有更好的方法?

  if (command.ExecuteNonQuery() <= 0) _success = false; 

      command.Connection.Close(); 

      if (_success) 
      { 
       return true; 
      } 

      throw new Exception("An error has occured whilst trying to add a entity"); 
     } 
     catch (Exception ex) 
     { 
      AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex)); 
      return false; 
     } 
    } 

在上面的例子中是否有更好的方法來處理異常?

在此先感謝您的幫助。

克萊爾

+2

除了Rob Stevenson-Leggetts的回答,我還會讓捕捉異常更具體。例如首先捕獲一個SqlException,因爲它將包含關於實際錯誤和堆棧跟蹤的更多特定信息。 讓catch(Exception ex)作爲最後的catch-block。 – 2010-08-10 10:02:04

回答

3

這裏有很多錯誤。

a。您正在使用內聯SQL並將我只能假設爲用戶生成的數據注入到它中。這是一個安全風險。使用parameterised query

b。你是異常處理是好的,但如果發生錯誤,這將使連接斷開。我會這樣寫:

public bool AddEntity(int parentId, string description) 
{ 
    try 
    { 
     //Assuming you have a string field called connection string 
     using(SqlConnection conn = new SqlConnection(_connectionString)) 
     { 
      SqlParameter descriptionParam = new SqlParameter("@description", SqlDbType.VarChar, 11); 
      descriptionParam.Value = description; 

      SqlParameter parentIdParam = new SqlParameter("@parentId", SqlDbType.Int, 4); 
      parentIdParam.Value = parentId; 

      //Bit confused about the GetPath bit. 
      SqlCommand command = new SqlCommand("INSERT Structure (Path,Description) " + 
              "VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL),@description)", conn); 

      command.Parameters.Add(descriptionParam); 

      if (command.ExecuteNonQuery() <= 0) _success = false; 
     } 

     if (_success) 
     { 
      return true; 
     } 

     //This isn't really an exception. You know an error has a occured handle it properly here. 
     throw new Exception("An error has occured whilst trying to add a entity"); 
    } 
    catch (Exception ex) 
    { 
     AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex)); 
     return false; 
    } 
+0

用於參數化查詢。我知道這是存在的,但不知道它叫什麼,或者看看:) – 2010-08-10 09:22:19

+0

感謝這個Rob,快速的問題我該如何處理SqlException? – ClareBear 2010-08-10 13:09:56

2

您可以利用IDisposable接口,以及一個using塊的力量。

using(var connection = new Connection()) // Not sure what _connection is, in this method, so making pseudo-code 
{ 
    // ... work with connection 
} 

即使發生異常,也會關閉連接。它變成(或多或少):

var connection = new Connection(); 

try 
{ 
    // ... work with connection 
} 
finally 
{ 
    connection.Dispose(); 
} 

在這種情況下,將關閉連接。

相關問題