Problem with an update statement
I want the statement update the database by 1 each time I enter a specific page..But it seems to update it by 3 :(
public static void UpdateThreadView(int threadID)
{
StringBuilder sb = new StringBuilder();
sb.Append("UPDATE dbo.Threads");
sb.Append(" SET Views=(Views+1)");
sb.Append(" WHERE ThreadsID=@ThreadID");
string myConnectionString = AllQuestionsPresented.connectionString;
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
开发者_StackOverflow myConnection.Open();
SqlCommand sqlCommand = new SqlCommand(sb.ToString(), myConnection);
sqlCommand.Parameters.Add("@ThreadID", SqlDbType.Int);
sqlCommand.Parameters["@ThreadID"].Value = threadID;
sqlCommand.ExecuteNonQuery();
}
}
Set a breakpoint in your code and run in the visual studio debugger.
I'm betting this gets called 3 times due to a combination of postback and events.
Alternatively you could use SQL Profiler to see if multiple updates happen.
sparks advice is really good. Learn to know the debugger. There are some real sweet things you can do with breakpoints and the Immediate window that will help you become a much more efficient.
On a site note. How you use the Stringbuilder is not very efficient. Generally speaking unless you are doing things in a loop avoid the stringbuilder as there are some overhead to the creation of it.
var str = "UPDATE dbo.Threads"
+ " SET Views=(Views+1)"
+ " WHERE ThreadsID=@ThreadID";
This type of code will be optimized by the compiler to be one string assignment anyway. I created a small test which showed that on 1000000 iterations the stringbuilder takes 467 ms while string concatenation takes 8. It won't kill your application but might be good to know.
精彩评论