首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在C#中捕获SQLException?

如何在C#中捕获SQLException?
EN

Stack Overflow用户
提问于 2011-05-11 18:38:05
回答 6查看 10.9K关注 0票数 1

在这里,我试图使用SMO Ojects.In Sqlserver中的innerexception来捕获sql异常。我得到了以下错误消息

代码语言:javascript
复制
Msg 121, Level 15, State 1, Procedure test_sp_syntaxtext, Line 124
The select list for the INSERT statement contains more items than the insert list.

但是通过使用下面的代码

代码语言:javascript
复制
catch (Exception ex)
          {
           ErrorFlag = true;
           //ex.Source.ToString();
           e2dInsertAndGenerateErrorLog(ex.InnerException.Message.ToString(), FileName, "CHECKINAPPLY", PathName, "ErrorLog.Err");
          }

我拿到这个了

代码语言:javascript
复制
The select list for the INSERT statement contains more items than the insert list.

我还需要缓存这一行

代码语言:javascript
复制
Msg 121, Level 15, State 1, Procedure test_sp_syntaxtext, Line 124

有什么建议吗?

编辑:

代码语言:javascript
复制
  StreamReader str = new StreamReader(FiletextBox.Text.ToString());
  string script = str.ReadToEnd();
  str.Dispose();
  SqlConnection conn = new SqlConnection("Data Source=xx;database=xxx;User id=sx;Password=xxxx");
  Server server = new Server(new ServerConnection(conn));
  server.ConnectionContext.ExecuteNonQuery(script);
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-05-11 18:40:21

使用SQLException

代码语言:javascript
复制
    catch (SqlException ex)
    {
        for (int i = 0; i < ex.Errors.Count; i++)
        {
            errorMessages.Append("Index #" + i + "\n" +
                "Message: " + ex.Errors[i].Message + "\n" +
                "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                "Source: " + ex.Errors[i].Source + "\n" +
                "Procedure: " + ex.Errors[i].Procedure + "\n");
        }
        Console.WriteLine(errorMessages.ToString());
    }
票数 8
EN

Stack Overflow用户

发布于 2011-05-11 18:40:23

代码语言:javascript
复制
catch (SqlException ex) { ... }
票数 1
EN

Stack Overflow用户

发布于 2011-05-11 18:41:31

看看你在http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.aspx上找到的属性

您将需要捕获SqlException,而不只是任何异常。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5962884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档