Tempo
Tempo

Reputation: 211

Unable to insert image in my Access Database

Well I have a simple MS Access database where the connection is fine but I keep getting the error

Syntax error in INSERT INTO Statement

private void btnSave_Click(object sender, EventArgs e)
{
   byte[] picbyte = System.IO.File.ReadAllBytes(imgFile);
   try
   {
      conn = new OleDbConnection(connstring);
      conn.Open();
      sqlcom = new OleDbCommand("INSERT INTO Image (Img) values (@Img)", conn);
      sqlcom.Parameters.AddWithValue("@Img", picbyte);
      sqlcom.ExecuteNonQuery();
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
   finally
   {
      conn.Close();
   }
}

My table's name is Image and the columns are ImgId (Autonumber) and Img (OLE Object)

Upvotes: 1

Views: 1235

Answers (3)

John Woo
John Woo

Reputation: 263723

Your table name (IMAGE) is data type. In order to escape that, you have to use brackets [ ].

command.CommandText = "INSERT INTO [Image] (Img) VALUES (@Img)";

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Try this:

byte[] picbyte = System.IO.File.ReadAllBytes(imgFile);
using (var connection = new OleDbConnection(connstring))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = "INSERT INTO [Image] (Img) VALUES (@Img)";
    command.Parameters.AddWithValue("@Img", picbyte);
    command.ExecuteNonQuery();
}

Upvotes: 4

Dor Cohen
Dor Cohen

Reputation: 17080

This problem may occur if your database table contains column names that use Microsoft Jet 4.0 reserved words, can you try to change your table name?

Upvotes: 2

Related Questions