C# 不捕获执行非查询异常

C# doesn't catch execute non query exception
2021-11-25
  •  译文(汉语)
  •  原文(英语)

我有这段代码,它调用存储过程将数据"插入"到 SQL 中的表中.

using (SqlConnection connection = new SqlConnection(Global_Variables.DBcon))
{
    SqlCommand cmd = new SqlCommand("sp_WinApps_Import_ERData", connection);
    cmd.CommandType = CommandType.StoredProcedure;
    connection.Open();
    try
    {
        cmd.ExecuteNonQuery();
        Console.WriteLine("file imported!");
    }

    catch (SqlException ex)
    {
        Console.WriteLine("BATCH ID ALREADY EXISTS!" + ex.Message );
    }
    finally
    {
        connection.Close();
    }
}

但问题是,它没有捕捉到"try-catch 方法"中的错误,我不知道为什么,但我的代码是正确的.

错误说:"违反唯一键约束'Cons_BatchID'.无法在对象'dbo.tbl_WinApps_FileHeader'中插入重复键.超时到期.在操作完成之前超时时间已过或服务器没有响应.该语句已被终止."

解决过程1

我解决了伙计们.转到调试> 异常,我只是在公共语言运行时异常中"取消选中了抛出的复选框"

I have this code that calls the stored procedure to 'insert' data to tables in SQL.

using (SqlConnection connection = new SqlConnection(Global_Variables.DBcon))
{
    SqlCommand cmd = new SqlCommand("sp_WinApps_Import_ERData", connection);
    cmd.CommandType = CommandType.StoredProcedure;
    connection.Open();
    try
    {
        cmd.ExecuteNonQuery();
        Console.WriteLine("file imported!");
    }

    catch (SqlException ex)
    {
        Console.WriteLine("BATCH ID ALREADY EXISTS!" + ex.Message );
    }
    finally
    {
        connection.Close();
    }
}

but the problem is, it doesn't catch the error in the 'try-catch method' i dont know why but my code is correct.

The Error says: "Violation of UNIQUE KEY constraint 'Cons_BatchID'. Cannot insert duplicate key in object 'dbo.tbl_WinApps_FileHeader'. Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated."

Solutions1

I solved it guys. Go to Debug > Exceptions and i just 'unchecked thrown checkbox' in Common Language Runtime Exceptions

转载于:https://stackoverflow.com/questions/15238422/c-sharp-doesnt-catch-execute-non-query-exception

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入