简体   繁体   English

SQL插入查询未执行而未在C#中引发任何异常

[英]SQL Insert Query not executing without throwing any exception in c#

I wrote an insert function for a discussion forum website to insert new discussion threads in database. 我为论坛论坛网站编写了一个插入函数,用于在数据库中插入新的讨论线程。 The function is as follows: 功能如下:

public int createDiscuss(Discussion dis)
    {
        query = "insert into [MyForums].[dbo].[Discussions](desid, text, date, time, replyto, uid, isPrivate) values(@id, @text, @date, @time, @replyto, @uid, @pvp)";
        string did=getDesID();
        if (did == null)
            return -1;
        try
        {
            com = new SqlCommand(query, con);
            com.Parameters.AddWithValue("@id", did); 
            com.Parameters.AddWithValue("@text", dis.gettext()); 
            com.Parameters.AddWithValue("@date", SqlDateTime.Parse(DateTime.Now.ToString())); 
            com.Parameters.AddWithValue("@time", SqlDateTime.Parse(DateTime.Now.ToString()));
            com.Parameters.AddWithValue("@replyto", dis.getreplyto());
            com.Parameters.AddWithValue("@uid", dis.getuid());
            if (dis.IsPrivate() == false)
            { com.Parameters.AddWithValue("@pvp", 1); }
            else
            { com.Parameters.AddWithValue("@pvp", 2);  }
            con.Open();
            int r=com.ExecuteNonQuery();
            if (r <= 0)
            {
                return -1;
            }
            con.Close();

        }
        catch (Exception)
        {
            return -1;
        }
        return 0;
    }

This function if encounters an error or exception than it return -1 and which is checked by the calling function and then the calling function shows error. 如果遇到错误或异常,此函数将返回-1,并由调用函数进行检查,然后调用函数显示错误,则该函数将返回-1。 The problem is that this insert function is not executing query. 问题在于此插入功能未执行查询。 When I checked that if the values are properly passing or not to the AddWithValue function as an argument, I found that every value is passed as it was given on the asp.net page. 当我检查值是否正确传递给AddWithValue函数作为参数时,我发现每个值都按asp.net页上给出的值传递。 But when control comes to com.ExecuteNonQuery() function. 但是当控制权转到com.ExecuteNonQuery()函数时。 It is returning -1 that is error. 它返回-1,这是错误。 Can anyone tell me whats wrong with my code? 谁能告诉我我的代码有什么问题吗? or how can I check why com.ExecuteNonQuery() not returning any effected row?? 或如何检查com.ExecuteNonQuery()为什么不返回任何受影响的行?


This exception showing 此异常显示

 A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code 

That being said, SQL Profiler is your friend here. 话虽如此,SQL Profiler是您的朋友。 Grab the generated sql from profiler and run it in SQL mgmt studio. 从探查器中获取生成的sql并在SQL mgmt studio中运行它。 I am 99% confident the answer will be obvious. 我有99%的信心,答案将很明显。 If not, then please update your answer with the generated sql from profiler, and we'll take it from there. 如果不是,请使用从事件探查器生成的sql更新您的答案,然后从那里获取答案。

If you need some guidance on SQL Profiler, a simple Google search brings up many options: SQL Profiler Search 如果您需要有关SQL Profiler的一些指导,简单的Google搜索会带来很多选择: SQL Profiler搜索

  • You should close your connection in a finally block. 您应该在finally块中关闭连接。 Any exception you encounter before con.Close(); 您在con.Close();之前遇到的任何异常con.Close(); will result in your connection being left open. 将导致您的连接保持打开状态。 That could be the error here (depending on the scope of con ) 这可能是这里的错误(取决于con的范围)

  • You should not swallow the exception, but log it. 您不应吞下该异常,而应将其记录下来。 Then you can examine the errors properly. 然后,您可以正确检查错误。 If you don't have logging, get logging. 如果您没有日志记录,请获取日志记录。 But in the meantime, look at the exception you have caught using the debugger. 但是与此同时,请查看使用调试器捕获的异常。

  • You should also catch more specific exceptions, so that you can tell the difference between a connectivity error and a chronic bug in the application. 您还应该捕获更多特定的异常,以便可以分辨出连接错误和应用程序中的长期错误之间的区别。 Check which exceptions are likely to be thrown by the methods you are calling. 检查您正在调用的方法可能抛出哪些异常。 For example, con.Open() can throw these: 例如,con.Open()可以抛出以下内容:

SqlException

InvalidOperationException

So catch those first, and catch Exception last. 因此,首先捕获那些Exception最后捕获Exception

Depending on the type of exception you can return a different error code and/or log at a different level of severity. 根据异常的类型,您可以返回不同的错误代码和/或以不同的严重性级别记录日志。


Also, figure out a way (using profiling or just copy+paste) to run that query against the database and see what happens. 另外,找出一种方法(使用性能分析或仅复制+粘贴)以对数据库运行该查询,并查看会发生什么情况。 For example, are you sure this part is right: 例如,您确定这部分是正确的:

        com.Parameters.AddWithValue("@date",
            SqlDateTime.Parse(DateTime.Now.ToString())); 
        com.Parameters.AddWithValue("@time",
            SqlDateTime.Parse(DateTime.Now.ToString()));

@date and @time are identical. @date@time相同。 Are the database values identical too and are the columns both expecting strings? 数据库值是否也相同,并且列都需要字符串吗?

You need to do some basic debugging. 您需要进行一些基本的调试。 Setup your code like: 设置代码如下:

catch(Exception ex)
{
  return -1;
}

Set a break point on return, and see what the Exception is. 在返回时设置一个断点,并查看异常是什么。

you are probably not reaching the int r=com.ExecuteNonQuery(); 您可能未达到int r=com.ExecuteNonQuery(); code. 码。 Could be an error on the con.Open(); 可能是con.Open();上的错误con.Open(); method. 方法。

Could you throw a new exception inside your catch and show us the actual error? 您能否在捕获中抛出一个新异常并向我们显示实际错误?

A challenge with your current code is that "-1" is returned in several different scenarios: 当前代码的一个挑战是在几种不同的情况下返回“ -1”:

  • Exception occurs 发生异常
  • result of getDesID is null getDesID的结果为null
  • INSERT statement fails to insert a row INSERT语句无法插入行

One simple way to check this would be to return a different number (say -2 or -3) from each point of failure. 一种简单的检查方法是从每个故障点返回不同的数字(例如-2或-3)。 That way you can determine where the error is being raised without changing your code much or attaching a debugger. 这样一来,您就可以确定发生错误的位置,而无需太多更改代码或附加调试器。

It appears to me that the issue is not likely your SQL INSERT statement - if the statement itself was invalid or violated a database constraint, SQL Server would raise an exception back to you which would be caught by your Exception handler. 在我看来,该问题不太可能是您的SQL INSERT语句-如果该语句本身无效或违反了数据库约束,则SQL Server将向您引发一个异常,该异常将由您的Exception处理程序捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM