Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A few things stand out:</p> <ul> <li><p>You don't show where the SqlConnection is instantiated, so it's not clear that you're disposing it properly.</p></li> <li><p>You shouldn't be swallowing exceptions in the loop - better to handle them in a top level exception handler.</p></li> <li><p>You're instantiating new parameters on each iteration through the loop - you could just reuse the parameters.</p></li> </ul> <p>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):</p> <pre><code>using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlCommand updateCommand = new SqlCommand(update, conn)) { string uid = Session["uid"].ToString(); updateCommand.Parameters.AddWithValue("@ID", uid); updateCommand.Parameters.AddWithValue("@qnum", i); updateCommand.Parameters.Add("@answer", System.Data.SqlDbType.VarChar); for (int i = tempStart; i &lt;= tempEnd; i++) { updateCommand.Parameters["@answer"] = Request.Form[i.ToString()]; updateCommand.ExecuteNonQuery(); } } } </code></pre> <p>Or to use a transaction to ensure all or nothing:</p> <pre><code>using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction transaction = conn.BeginTransaction()) { using (SqlCommand updateCommand = new SqlCommand(update, conn, transaction)) { string uid = Session["uid"].ToString(); updateCommand.Parameters.AddWithValue("@ID", uid); updateCommand.Parameters.AddWithValue("@qnum", i); updateCommand.Parameters.Add("@answer", System.Data.SqlDbType.VarChar); for (int i = tempStart; i &lt;= tempEnd; i++) { updateCommand.Parameters["@answer"] = Request.Form[i.ToString()]; updateCommand.ExecuteNonQuery(); } transaction.Commit(); } } // Transaction will be disposed and rolled back here if an exception is thrown } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload