2013-08-28 71 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