Replaces Question: Update multiple rows into SQL table
Here’s a Code Snippet to update an exam results set. DB structure is as given, but I can submit Stored Procedures for inclusion (Which are a pain to modify, so I save that until the end.)
The question: Is there a better way using SQL server v 2005.,net 2.0 ?
string update = @'UPDATE dbo.STUDENTAnswers SET ANSWER=@answer WHERE StudentID =@ID and QuestionNum =@qnum'; SqlCommand updateCommand = new SqlCommand( update, conn ); conn.Open(); string uid = Session['uid'].ToString(); for (int i= tempStart; i <= tempEnd; i++) { updateCommand.Parameters.Clear(); updateCommand.Parameters.AddWithValue('@ID',uid); updateCommand.Parameters.AddWithValue('@qnum',i); updateCommand.Parameters.AddWithValue('@answer', Request.Form[i.ToString()]); try { updateCommand.ExecuteNonQuery(); } catch { } }
A few things stand out:
You don’t show where the SqlConnection is instantiated, so it’s not clear that you’re disposing it properly.
You shouldn’t be swallowing exceptions in the loop – better to handle them in a top level exception handler.
You’re instantiating new parameters on each iteration through the loop – you could just reuse the parameters.
Putting this together it could look something like the following (if you don’t want to use a transaction, i.e. don’t care if some but not all updates succeed):
Or to use a transaction to ensure all or nothing:
Finally, another problem is that you are mixing UI code (e.g. Request.Form) with data access code. It would be more modular and testable to separate these – e.g. by splitting your application into UI, Business Logic and Data Access layers.