Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Syntax error in INSERT INTO statement" when adding record to Access database

Tags:

c#

ms-access

I've searched for hours for a solution to this problem but nothing I've read has helped. I'm getting this error when trying to add this record to an Access database. The file I'm trying to save into is named Cats.accdb, with a table named Cats.

Table column names:
CatId (type: text)
CatName (text)
Hair (text)
Size (text)
CareType (text)
Notes (text)
AdoptDate (date/time general date), Weight (double), Age (integer) (I've commented any reference to these columns out in the C# code to attempt to debug with just plain old text boxes. At first I thought it was because of something to do with using a DateTimePicker, but it still throws the error after commenting out.)

C# code:

Cat temp = new Cat(txtCatName.Text, txtHair.Text, txtSize.Text, txtCareType.Text, txtNotes.Text);

public string AddCat()
    {
        string strFeedback = "";

        string strSQL = "INSERT INTO Cats (CatName, Hair, Size, CareType, Notes) VALUES (@CatName, @Hair, @Size, @CareType, @Notes)"; 

        OleDbConnection conn = new OleDbConnection();

        string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Data\Cats.accdb; Persist Security Info=False;";
        conn.ConnectionString = strConn; 

        OleDbCommand comm = new OleDbCommand();
        comm.CommandText = strSQL;  
        comm.Connection = conn; 
        comm.Parameters.AddWithValue("@CatName", CatName); 
        comm.Parameters.AddWithValue("@Hair", Hair);
        comm.Parameters.AddWithValue("@Size", Size);
        comm.Parameters.AddWithValue("@CareType", CareType);
        comm.Parameters.AddWithValue("@Notes", Notes);
        //comm.Parameters.AddWithValue("@AdoptDate", AdoptDate);
        //comm.Parameters.AddWithValue("@Weight", Weight);
        //comm.Parameters.AddWithValue("@Age", Age);

        {
            conn.Open();
            strFeedback = comm.ExecuteNonQuery().ToString() + " record has been added successfully!";
            conn.Close();
        }
        catch (Exception err)
        {
            strFeedback = "ERROR: " + err.Message;
        }
        return strFeedback;

lblFeedback.Text = temp.AddCat();

Thanks for any help you can give!

like image 751
leoraelkins Avatar asked Jan 08 '23 11:01

leoraelkins


1 Answers

Size is a reserved keyword. Add brackets around the name to specify that it's an identifier:

string strSQL = "INSERT INTO Cats (CatName, Hair, [Size], CareType, Notes) VALUES (@CatName, @Hair, @Size, @CareType, @Notes)"; 

Alternatively, change the field name to something that is not a keyword.

like image 175
Guffa Avatar answered Jan 17 '23 15:01

Guffa