JoshF91
JoshF91

Reputation: 139

C# Syntax Error - INSERT INTO statement. Access Database.

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?

Upvotes: 1

Views: 8008

Answers (2)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79979

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();
  }
}

Upvotes: 9

Francesco Milani
Francesco Milani

Reputation: 415

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.

Upvotes: 0

Related Questions