Search code examples
c#ms-accessado.netoledb

Insert query for ms-access with Oledb object getting exception of not a valid query


I'm using the following code and it is giving the invalid Insert command exception.

row the DataRow object to be added to the database , conn is the OleDBConnection object.

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = `"Insert Into Appointments(ID,Body,End,Location,Start,Subject,Properties)"
                                                + "Values(@ID,@Body,@End,@Location,@Start,@Subject,@Properties)";


cmd.Parameters.Add("@ID", OleDbType.WChar).Value = row[0].ToString();
cmd.Parameters.Add("@Body", OleDbType.WChar).Value = row[1].ToString();
cmd.Parameters.Add("@End", OleDbType.Date).Value =  Convert.ToDateTime(row[2]).Date.ToLongDateString();
cmd.Parameters.Add("@Location", OleDbType.WChar).Value = row[3].ToString();
cmd.Parameters.Add("@Start", OleDbType.Date).Value = Convert.ToDateTime(row[4]).Date.ToLongDateString();
cmd.Parameters.Add("@Subject", OleDbType.WChar).Value = row[5].ToString();
cmd.Parameters.Add("@Properties", OleDbType.WChar).Value = row[6].ToString();


                conn.Open();                    
                cmd.ExecuteNonQuery();          //At this line exception is generating
                conn.Close();

Please help me in this.


Solution

  • You've got one (possibly more) reserved word in your table's field names.

    The field name End ... at the very least.

    Try

    cmd.CommandText = `"Insert Into Appointments(ID,Body,[End],Location,Start,Subject,Properties)"
                                                    + "Values(@ID,@Body,@End,@Location,@Start,@Subject,@Properties)";