1

This is my code which I am getting syntax error in my INSERT statement for:

string strSql = "INSERT INTO Responses (OCR, DeadlineDate, OCR Title) VALUES ('"+textBox5.Text+"','"+textBox7.Text+"', '"+textBox6.Text+"')";

OleDbConnection newConn = new OleDbConnection(strProvider);
OleDbCommand dbCmd = new OleDbCommand(strSql, newConn);

newConn.Open();
dbCmd.ExecuteNonQuery();

any ideas?

Ankush Madankar
  • 3,689
  • 4
  • 40
  • 74
JoshF91
  • 99
  • 1
  • 3
  • 11
  • 2
    Avoid your current injection vulnerability; http://stackoverflow.com/questions/5893837/using-parameters-inserting-data-into-access-database – Alex K. Jan 09 '14 at 14:11

2 Answers2

9

The column name OCR Title is invalid, you have to escape it using [] like [OCR Title]:

INSERT INTO Responses (OCR, DeadlineDate, [OCR Title]) VALUES( ...

Also, please try to use parametrized queries instead of concatenating the values:

string strSql = "INSERT INTO Responses (OCR, DeadlineDate, [OCR Title]) VALUES (?, ?, ?)";

using (OleDbConnection newConn = new OleDbConnection(strProvider))
{
  using (OleDbCommand dbCmd = new OleDbCommand(strSql, newConn))
  {
    dbCmd.CommandType = CommandType.Text;
    dbCmd.Parameters.AddWithValue("OCR", textBox5.Text);
    dbCmd.Parameters.AddWithValue("DeadlineDate", textBox7.Text);
    dbCmd.Parameters.AddWithValue("[OCR Title]", textBox6.Text);
    newConn .Open();
    dbCmd.ExecuteNonQuery();
  }
}
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
  • Better to always put brackets around column names, when upgrading to a new database version who knows whether e.g. OCR becomes a keyword. – Silvermind Jan 09 '14 at 14:10
0

I guess the syntax error isn't related to c# but to SQL statement.

Maybe you need escape on textBoxes values and text qualifier for "OCR Title" table name.

Francesco Milani
  • 415
  • 4
  • 11