asp.netsql-server

"Incorrect syntax near ')'." from cmd.ExecuteNonQuery();


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]\r\n           ([column])\r\n\r\n     VALUES\r\n           ("+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:

Any help is appreciated. Thank you!


Solution

  • 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.