Pregunta

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. 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. But when control comes to com.ExecuteNonQuery() function. It is returning -1 that is error. Can anyone tell me whats wrong with my code? or how can I check why com.ExecuteNonQuery() not returning any effected row??


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
¿Fue útil?

Solución

  • You should close your connection in a finally block. Any exception you encounter before con.Close(); will result in your connection being left open. That could be the error here (depending on the scope of 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:

SqlException

InvalidOperationException

So catch those first, and catch Exception last.

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. Are the database values identical too and are the columns both expecting strings?

Otros consejos

That being said, SQL Profiler is your friend here. Grab the generated sql from profiler and run it in SQL mgmt studio. I am 99% confident the answer will be obvious. If not, then please update your answer with the generated sql from profiler, and we'll take it from there.

If you need some guidance on SQL Profiler, a simple Google search brings up many options: SQL Profiler Search

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(); code. Could be an error on the 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:

  • Exception occurs
  • result of getDesID is null
  • INSERT statement fails to insert a row

One simple way to check this would be to return a different number (say -2 or -3) from each point of failure. 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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top