skip to Main Content

After updating from System.Data.SqlClient to Microsoft.Data.SqlClient in my ASP.NET webforms app, I encountered a problem when trying to run cmd.ExecuteNonQuery(); in this code:

protected void Button1_Click(object sender, EventArgs e)
{
     con.Open();
     SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[table]rn           ([column])rnrn     VALUESrn           ("+TextBox1.Text+");"); -- Yes, I know, I will add SQL parameters once I am done with this error and any future errors

     cmd.Connection = con;
     cmd.ExecuteNonQuery();
     con.Close();

     Response.Write("<script>alert('added')</script>");
}

When I run the webform in my browser and activate Button1_Click,
I get an error for cmd.ExecuteNonQuery();:

Microsoft.Data.SqlClient.SqlException: Incorrect syntax near ‘)’

I have tried:

  • Switching some lines of code around, gives even more errors
  • Removing the line of code with the error, fixes the error but the query does not execute (of course)
  • Removing the "Non" in ExecuteNonQuery();

Any help is appreciated. Thank you!

2

Answers


  1. The first obvious bug is this: when you call new SqlCommand(), you compose its string parameter value out of string literals (immediate constants) and the value returned by the property TextBox1.Text. That is, the UI user can enter any arbitrary text. You did not inform us what content this text box contained during your test, and this is not really important. The entire idea is a big no-no.

    Your code cannot be fixed in any simple way based on your existing code. It should be completely redesigned. The details of the proper solution depend on the ultimate goal of your application. Using SQL parameters is the right way — see also the comments to your question.

    Login or Signup to reply.
  2. The error occurs because the strings have to be enclosed in single quotation marks in SQL. Try adding single quotation marks before and after TextBox1.Text, like this:

    "... VALUES ('" + TextBox1.Text + "');" 
    

    Like you said, it would be even better to enhance this code with SQL parameters to mitigate SQL injection risks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search