Search code examples
c#ms-accessinsertinsert-intoms-access-2016

Failing to insert data into MS Access database (syntax error in INSERT INTO statement.)


I wrote this code to insert data into my Microsoft Access database but it is failing and throws this error:

Syntax error in INSERT INTO statement.

Here is my code:

  // Open the connection to the database.
  connection.Open();
  OleDbCommand dbcmd = new OleDbCommand();
  dbcmd.Connection = connection;

  // Inserting Data.
  dbcmd.CommandText = "insert into ConveyanceBill1 (empname, from) values('" + txtEmployee.Text + "','" + txtFrom.Text + "')";
  dbcmd.ExecuteNonQuery();
  MessageBox.Show("Sucessfully Added!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  connection.Close();

But if I change this line:

// Inserting Data.
dbcmd.CommandText = "insert into ConveyanceBill1 (empname, from) values('" + txtEmployee.Text + "','" + txtFrom.Text + "')";

To this Line:

// Inserting Data.              
dbcmd.CommandText = "insert into ConveyanceBill1 (empname, designation) values('" + txtEmployee.Text + "','" + txtDesignation.Text + "')";

It works flawlessly. I can't find why it is not working.Here is my database table in Design view:

Designview of Database Table

I tried a lot, but I still don't get why it is not working.


Solution

  • FROM is a reserved keyword in Microsoft OLE DB Provider. You might wanna use it with square brackets like [FROM]. But as a best practice, change it to non-reserved word.

    But more important

    You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

    Also use using statement to dispose your OleDbConnection and OleDbCommand automatically instead of calling Close or Dispose methods manually.

    using(var connection = new OleDbConnection(conString))
    using(var dbcmd = connection.CreateCommand())
    {
        dbcmd.CommandText = "insert into ConveyanceBill1 (empname, from) values(?, ?)";
        dbcmd.Parameters.Add("?", OleDbType.VarWChar).Value = txtEmployee.Text;
        dbcmd.Parameters.Add("?", OleDbType.VarWChar).Value = txtFrom.Text;
       
        connection.Open();
        int effectedRows = dbcmd.ExecuteNonQuery();
        if(effectedRows > 0)
        {
           MessageBox.Show("Sucessfully Added!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }   
    }