Search code examples
c#ms-accesssyntax-errorsql-insertsqlexception

Syntax error in INSERT INTO statement using C# with ms-access


I am having trouble figuring out what is wrong with my code. I am trying to add a record in my Access Db through C# but was confronted with an exception that says I have a wrong syntax in my SQL statement.

 private void buttonSUB_Click(object sender, EventArgs e)
    {
        string Adrs = textADRS.Text;
        string Fname = textFN.Text;
        string Mname = textMN.Text;
        string Lname = textLN.Text;
        string Pos = textPOS.Text;

        try
        {

            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\Users\\genesis\\Documents\\Database1.accdb";
            OleDbCommand cmd = new OleDbCommand("Insert into Employees (FN,MN,LN,Address,Position) Values (@FirstName,@MidName,@LastName,@Address,@Position)",con);
            cmd.Parameters.Add(new OleDbParameter("@FirstName", Fname));
            cmd.Parameters.Add(new OleDbParameter("@MidName", Mname));
            cmd.Parameters.Add(new OleDbParameter("@LastName", Lname));
            cmd.Parameters.Add(new OleDbParameter("@Address", Adrs));
            cmd.Parameters.Add(new OleDbParameter("@Position", Pos));
            con.Open();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Record Submitted", "Nice!");
            con.Close();
        }

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



    }

Solution

  • From Access SQL Reserved Words List, POSITION already defined as reserved keyword.

    If you use a reserved word or symbol to name a field in a table, Access warns you that the word is reserved and that you might encounter errors when referring to the field. You might also encounter errors if you use a reserved word to name a control, an object, or a variable.

    If a reserved word is already in use, you can avoid error messages by surrounding each occurrence of the word with brackets ([ ]).

    Hence, you need to add square brackets to use it as table name:

    OleDbCommand cmd = new OleDbCommand(
                     @"INSERT INTO Employees (FN, MN, LN, Address, [Position]) 
                       VALUES (@FirstName, @MidName, @LastName, @Address, @Position)", con);
    

    NB: Reserved words are case-insensitive in Access usage, thus every occurrences which use reserved words must placed inside square brackets.