I've encountered this error while adding an image to the database. (column's data type is not binary, but image)

error message is attached on this post.

this is my code for adding images to DB.

byte[] ins = GetBinaryFile(txtDIR.Text);
                int x = 1;
                string comm = "INSERT INTO pictable (picDirectory, pic, caption) values(" +
                    "'" + txtDIR.Text + "'," +
                    "'" + ins + "'," +
                    "'" + txtCaption.Text +  "')";

                OleDbCommand cm = new OleDbCommand(comm, cn);

                cm.Parameters.Add(new OleDbParameter("@picID",
                (object)x));
                cm.Parameters.Add(new OleDbParameter("@picDirectory",
                (object)txtDIR.Text));
                cm.Parameters.Add(new OleDbParameter("@pic",
                (object)ins));
                cm.Parameters.Add(new OleDbParameter("@caption",
               (object)txtCaption.Text));

                cm.ExecuteNonQuery();

Edited 4 Years Ago by kevinyu: n/a

Attachments Untitled.png 39.71 KB

Here is a sample of how to insert/update image data. The sample code uses SqlClient instead of OleDB, but it should be a similar process.

Your algorithm should be:

1. Read image file into MemoryStream using the Image.Save function.
2. Convert the MemoryStream to a byte[] using Stream.ToArray function.
3. Add parameter to the SQL command, set value to the byte[] and DbType to DbType.Image.
4. Execute the SQL via the ExecuteNonQuery function.

Hope this helps :)

EDIT: Also, you aren't setting the parameters correctly in the SQL. Your query should look like this:

string comm = "INSERT INTO pictable (picId, picDirectory, pic, caption) values(@picId, @picDirectory, @pic, @caption)";

Edited 4 Years Ago by darkagn: n/a

Your main problem was you only specify 3 value to be updates, then you add 4 parameters!

Next:
What exact data type are the columns in the data table?
My assumption:
- pic id - integer
- pic - image (you must pass a byte array to db)
- caption - varchar (50 length)

This is how you must have, and then you do:

byte[] ins = GetBinaryFile(txtDIR.Text);
int x = 1;
string comm = "INSERT INTO pictable (pic id, picDirectory, pic, caption) values(@picID, @picDirectory, @pic, @caption)";

OleDbCommand cm = new OleDbCommand(comm, cn);
cm.Parameters.Add("@picID", OleDbType.Int).Value = x; //no object casting!
cm.Parameters.Add("@picDirectory", OleDbType.VarChar, 50).Value = txtDIR.Text;
cm.Parameters.Add("@pic", OleDbType.Image).Value = ins;
cm.Parameters.Add("@caption", OleDbType.VarChar, 50).Value = txtCaption.Text;
cm.ExecuteNonQuery();

Hope it helps,
bye

This question has already been answered. Start a new discussion instead.