0

I want to connect a Windows Form app with SQL Server and insert values from the app textboxes to a database. When the button is clicked, I receive an error:

Incorrect syntax near the keyword "Group".

What is the problem? How can I insert this data?

 private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            string myconnection = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=StudBase;Integrated Security=True";
            string Query = "Insert Into StudentInfo (StudentID, Name,Surname,Group,Course,City,Sector,Average rating) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";

            SqlConnection Myconn = new SqlConnection(myconnection);
            SqlCommand Mycom = new SqlCommand(Query, Myconn);
            SqlDataReader Reader1;
            Myconn.Open();
            Reader1 = Mycom.ExecuteReader();
            MessageBox.Show("Save data");
            while (Reader1.Read())
            {

            }
            Myconn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

enter image description here

Tim M.
  • 53,671
  • 14
  • 120
  • 163

1 Answers1

-1

Use this for your query statement -

string Query = "Insert Into StudentInfo (StudentID,[Name],Surname,[Group],Course,City,Sector,[Average rating]) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";

Use [] for reserved keywords in SQL. Also the last column Average rating was not covered with [], as this column name has space then it should be quoted in [].