none
Syntax error but I can't find what's wrong? RRS feed

  • Question

  • so I'm trying to follow this tutorial https://www.youtube.com/watch?v=TIAOr2S6-SY&feature=youtu.be at 6:30-6:35
    and for some reason I get this error? I'm pretty sure I have followed the tutorial step by step.
    Can someone help me? I'm not sure what I'm meant to do.

            private void btn_Add_Click(object sender, EventArgs e)
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "insert into table values('" + studentIDTextBox.Text + "','" + firstNameTextBox.Text + "','" + lastNameTextBox.Text + "','" + markTextBox.Text + "')";
                cmd.ExecuteNonQuery();
                con.Close();

                MessageBox.Show("Record has been added to the Database.");
            }

    The error says System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'table'.'
    Saturday, June 15, 2019 11:32 AM

Answers

  • Couple of things.  In the video he was inserting into table1 not table.  If you have a column or table which is a keyword you need to surround it in [ ] for example [table]

    Never ever put values from a textbox into a sql statement directly it opens you up to sql injection use parameters instead

               cmd.CommandText = "insert into table1 values(@studentId,@firstName,@lastName)";

    cmd.Parameters.Add("@studentId",studentIDTextBox.Text);

    etc..



    • Edited by Ken Tucker Saturday, June 15, 2019 12:32 PM
    • Marked as answer by Anderuu Sunday, June 16, 2019 2:06 PM
    Saturday, June 15, 2019 12:31 PM

All replies

  • Couple of things.  In the video he was inserting into table1 not table.  If you have a column or table which is a keyword you need to surround it in [ ] for example [table]

    Never ever put values from a textbox into a sql statement directly it opens you up to sql injection use parameters instead

               cmd.CommandText = "insert into table1 values(@studentId,@firstName,@lastName)";

    cmd.Parameters.Add("@studentId",studentIDTextBox.Text);

    etc..



    • Edited by Ken Tucker Saturday, June 15, 2019 12:32 PM
    • Marked as answer by Anderuu Sunday, June 16, 2019 2:06 PM
    Saturday, June 15, 2019 12:31 PM
  • Hi Anderuu,

    Welcome to the MSDN forum.

    We are so glad to hear that your issue is solved and thanks for Ken's solution.

    If you have any other issues in the future, please feel free to let us know.

    Have a nice day!

    Best regards,

    Sara


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com

    Monday, June 17, 2019 3:22 AM
    Moderator