2013-08-28 68 views
0

我目前正在使用我的C#asp.net頁面上的SQL。 我值插入數據庫,但這時如果ID是重複的,我得到這個異常:C#將字符串與SqlExtension比較

{"Violation of PRIMARY KEY constraint 'PK_Section'. Cannot insert duplicate key in object 'dbo.Section'.\r\nThe statement has been terminated."} 

什麼我想要做的是把異常做這樣的事情:

if(exception=={"Violation of PRIMARY KEY constraint 'PK_Section'. Cannot insert duplicate key in object 'dbo.Section'.\r\nThe statement has been terminated."}) 
    //update values instead of insert 

我問題是我無法比較異常(這是一個字符串)與我從試圖複製ID得到的那個長「字符串」。

是否有無論如何,我可以比較這個,以便我可以正確工作解決這個錯誤?

+1

在嘗試插入之前檢測到衝突。這就是我們應該做的。 –

+0

嘗試使用exception.tostring()。equals(「違反PRIMARY KEY約束'PK_Section'。不能在對象'dbo.Section'中插入重複鍵'\ r \ n聲明已終止。」) – akhil

+2

@KingKing您的解決方案是在有多個用戶的系統中存在根本性缺陷。 – podiluska

回答

3

我會用一個try catch塊來檢查的SQLException。類似這樣的:

private bool SaveDocument() 
{ 
     bool saved = false; 
     try 
     { 
      Save(); 
      saved = true; 
     } 
     catch (Exception ex) 
     { 
      string errorTitle = Resources.SaveErrorCaption; 
      string errorText = Resources.SaveErrorText; 
      Exception initialEx = ex; 
      while (ex.InnerException != null) 
      { 
       if (ex.InnerException is SqlException) 
       { 
        int errorNo = ((SqlException)ex.InnerException).Number; 

        if (errorNo == 2627) 
        { 
         errorTitle = Resources.DuplicateEntryErrorTitle; 
         errorText = Resources.DuplicateEntryErrorMessage; 
        } 
       } 
       ex = ex.InnerException; 
      } 
      MsgBox.Show(errorTitle, errorText, 
       string.Format("{0}{1}StackTrace:{1}{2}", initialEx.Message, Environment.NewLine, initialEx.StackTrace), 
       MsgBoxButtons.OK, MsgBoxImage.Error); 
     } 
     return saved; 
} 
+2

'saved = false;'在catch塊中是多餘的。 –

+0

是的,你是對的...刪除:) – sevdalone