0

I'm trying to add student data into a database but keeps coming up with the error "incorrect syntax near the keyword 'Table'". I'm very new to using windows form does anybody know where I have gone wrong?

private void BTAddstudent_Click(object sender, EventArgs e)
{
    try
    {
        string myconnection = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\tayla\OneDrive\Documents\StudentPerformance\StudentPerformance\Studentdatabase.mdf; Integrated Security = True";

        string Query = "Insert Into Table (ID, First name, Last name, Course 1, Course 2, Course 3, Course 4, Course 5, Course 6, Course 7, Course 8, Course 9, Course 10) values('" + this.txtbxID.Text + "','" + this.txtbxfirstname.Text + "','" + this.txtbxlastname.Text + "','" + this.txtbxcourse1.Text
            + "','" + this.txtbxcourse2.Text + "','" + this.txtbxcourse3.Text + "','" + this.txtbxcourse4.Text + "','" + this.txtbxcourse5.Text + "','" + this.txtbxcourse6.Text + "','" + this.txtbxcourse7.Text
            + "','" + this.txtbxcourse8.Text + "','" + this.txtbxcourse9.Text + "','" + this.txtbxcourse10.Text + "')";

        SqlConnection myconn = new SqlConnection(myconnection);
        SqlCommand mycom = new SqlCommand(Query, myconn);
        SqlDataReader reader1;
        myconn.Open();
        reader1 = mycom.ExecuteReader();
        while (reader1.Read()) ;
        {
        }
        myconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
3
  • 4
    Use a parameterised query, if you don't know what that is, you need to research it, it will make it easier to spot mistakes, and it will stop sql injection attacks among other things Commented May 30, 2019 at 3:06
  • Ok thank you I will look it up. Commented May 30, 2019 at 3:13
  • 2
    The ten courses may also indicate to rethink your design. Usually there should be another table, where you insert rows for the courses people take. Commented May 30, 2019 at 3:26

1 Answer 1

1

If you named your table Table, you must use brackets because Table is a reserved word. You must also use brackets in your column names if you use spaces.

Your sql statement should be like this:

Insert Into [Table] (ID, [First name], [Last name], [Course 1], [Course 2], ...

Using parameterized query is better. It's easier to read and it prevents SQL injection attack.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.