Click here to Skip to main content
15,941,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
In my aspx page, I have a photo uploader using this uploader I upload images. I have to store this image into DB(SqlServer 2008) in a varbinary column. I read all bytes from that image and store in a byte array. If i try to insert this byte array in to DB table i will get an error. How can I insert this byte array in to DB using SQL query " Insert into ..................."

Thanks,
Velkumar
Posted

 
Share this answer
 
Comments
Zoltán Zörgő 17-May-12 6:56am    
Oh yes, this is a google task...
Velkumar Kannan 17-May-12 7:04am    
I want to insert without using sql parameters
Velkumar Kannan 17-May-12 7:27am    
I want to insert without using sql parameters. For eg: " Insert into table1(Imageid,ImageData) values(imgID, imgdata) ". here imgdata is a byte array type variable.
Savada Sin 18-Mar-15 3:43am    
Hi Velkumar Kannan, Could you pls tell me how to insert without using sql parameters? I do need that solution, thanks so much.
Use a parametrized query (you should be anyway to avoid SQL Injection attacks). This code inserts the Thumbnail image as a byte array:
C#
using (SqlConnection con = new SqlConnection(GenericData.DBConnection))
    {
    con.Open();
    byte[] bytes = Thumbnail.ToByteArray()
    using (SqlCommand cmd = new SqlCommand("INSERT INTO Images (Id, Location, Thumbnail) VALUES (@ID, @DS, @TN)", con))
        {
        cmd.Parameters.AddWithValue("@ID", Id);
        cmd.Parameters.AddWithValue("@DS", Location);
        cmd.Parameters.AddWithValue("@TN", bytes);
        cmd.ExecuteNonQuery();
        }
    }</pre>
 
Share this answer
 
Comments
Velkumar Kannan 17-May-12 7:04am    
I want to insert without using sql parameters
OriginalGriff 17-May-12 7:19am    
You can't, without converting it to a very, very long text string (base64 for example). If you want it stored as bytes, you need to use parameters. If you aren't using them anyway, then you are leaving your database wide open to accidental or deliberate damage.
Velkumar Kannan 17-May-12 7:27am    
I want to insert without using sql parameters. For eg: " Insert into table1(Imageid,ImageData) values(imgID, imgdata) ". here imgdata is a byte array type variable.
OriginalGriff 17-May-12 7:32am    
You

can't

do

it



.
Velkumar Kannan 17-May-12 7:45am    
Please give a solution pls

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900