C# Windows Form SQL Incorrect Syntax near Error for no reason

75 Views Asked by At

In the code I have, there is a Column I call [Product Name], it is fully defined in my sql server and there should be no problem. This code needs to add the data in TextBox1 to that Column, but I couldn't manage it. I keep getting the error "Incorrect Syntax near [Product Name]" even though I'm pretty sure it's Product Name. Can anyone help?

Code:

private void button2_Click(object sender, EventArgs e)
   {
       string datatoadd = textBox1.Text;
       try
       {
           SqlConnection con = new SqlConnection(conString);
           con.Open();
   
               string query = "INSERT INTO fiyat.dbo [Urun Ismi] VALUES (@EklenecekVeri)";
               using (SqlCommand komut = new SqlCommand(query, baglanti))
               {
                   komut.Parameters.AddWithValue("@DataToAdd" , datatoadd);
                   komut.ExecuteNonQuery();
               }
       baglanti.Close();
           MessageBox.Show("Data added succesfully, added data; ", datatoadd);
       }
       catch (Exception ex)
       {
           MessageBox.Show("Error ", ex.Message);
       }

I asked my friend for help with this code but he literally did nothing. He said you can use SqlDataReader but I am completely confused.

1

There are 1 best solutions below

0
Amit Mohanty On

The issue in your code might be related to the SQL query syntax. The column name [Urun Ismi] should be enclosed in square brackets, and there should be a table name specified after INSERT INTO. Also you have define a different parameter(@EklenecekVeri) in your query and pass a different one(@DataToAdd).

private void button2_Click(object sender, EventArgs e)
{
    string datatoadd = textBox1.Text;
    try
    {
        using (SqlConnection con = new SqlConnection(conString))
        {
            con.Open();
            string query = "INSERT INTO fiyat.dbo.YourTableName ([Urun Ismi]) VALUES (@DataToAdd)";
            using (SqlCommand komut = new SqlCommand(query, con))
            {
                komut.Parameters.AddWithValue("@DataToAdd", datatoadd);
                komut.ExecuteNonQuery();
            }
        }
        MessageBox.Show("Data added successfully: " + datatoadd);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }
}