1

I'm building an app with c# asp.net. I need to insert some data into database. Everything works fine, but i get problem with inserting an image.

My database table:

Order

OrderID int
description varchar(50)
numOfItems int
material varchar(50)
image varbinary(max)

My code for inserting data into database

protected void btnAddItem_Click(object sender, EventArgs e)
    {
        string filepath = fileUpload.PostedFile.FileName;
        string filename = Path.GetFileName(filepath);
        string ext = Path.GetExtension(filename);
        string contentType = String.Empty;

        switch (ext)
        {
            case ".jpg":
                contentType = "image/jpg";
                break;
            case ".png":
                contentType = "image/png";
                break;
            case ".gif":
                contentType = "image/gif";
                break;
            case ".pdf":
                contentType = "application/pdf";
                break;
        }
        if (contentType != String.Empty)
        {
            Stream fs = fileUpload.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            string kon = ConfigurationManager.ConnectionStrings["mk"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(kon))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Order(description, numOfItems, material, image"))
                {
                    cmd.Connection = conn;
                    cmd.Parameters.AddWithValue("@description", inputTextArea.Text);
                    cmd.Parameters.AddWithValue("@numOfItems", inputTextArea.Text);
                    cmd.Parameters.AddWithValue("@material", inputTextArea.Text);
                    cmd.Parameters.Add("@image", SqlDbType.VarChar).Value = bytes;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    Response.Write("Success!");
                }
            }
        }
    }

When i do that, i get the following error : Failed to convert parameter value from a Byte[] to a String.

Any ideas?

UPDATE - new error

Incorrect syntax near 'image '. error. any ideas?

aiden87
  • 929
  • 8
  • 25
  • 52

3 Answers3

2
cmd.Parameters.Add("@image", SqlDbType.VarChar).Value = bytes;

Your image is not of type VarChar you need to fix that. Most likely, you need Binary.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
2

For the parameter @image the passed value is a byte array but you ware specified that the input will be VarChar change it to Binary. so the statement that add specific parameter will be looks like the following

cmd.Parameters.Add("@image", SqlDbType.Binary).Value = bytes;

And you have to add the placeholders to your query, which means the query text should be like this:

"INSERT INTO Order(description, numOfItems, material, image)values(@description, @numOfItems,@material,@image)"
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • actually now i get Incorrect syntax near 'image '. error. any ideas? – aiden87 Nov 30 '16 at 07:40
  • @fokz8 : You have to add placeholders to the query, check the updates in my answer – sujith karivelil Nov 30 '16 at 07:45
  • that seems to solve that problem. but yet again i get another one...i also have "OrderID" as my primary key, but i didn't want to put it into my webform. So how do i create and input id, without user inputting it? btw, i get this error = "annot insert the value NULL into column 'OrderID', table '.dbo.Order'; column does not allow nulls. INSERT fails." – aiden87 Nov 30 '16 at 07:50
  • Make the column `OrderID` as auto increment in the table. so it will automatically updates as you inserted each row – sujith karivelil Nov 30 '16 at 07:53
  • Coool..! Always happy to help you – sujith karivelil Nov 30 '16 at 08:00
1

Change the SqlDbType based on your database column type :

Possible datatypes for saving images in SQL are :

String types:

Data types and Description :

binary(n) Fixed width binary string. Maximum 8,000 bytes

varbinary Variable width binary string. Maximum 8,000 bytes

varbinary(max) Variable width binary string. Maximum 2GB

image Variable width binary string. Maximum 2GB

cmd.Parameters.Add("@image", SqlDbType.image).Value = bytes;

or

// Replace 8000, below, with the correct size of the field
     cmd.Parameters.Add("@image", SqlDbType.VarBinary, 8000).Value = bytes;

Modify your SQL Command to :

SqlCommand("INSERT INTO Order(description, numOfItems, material, image) values (@description,@numOfItems,@material,@image)")
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Alina Anjum
  • 1,178
  • 6
  • 30
  • 53