简体   繁体   中英

Saving and retrieving image in SQL database from C# problem

I used this code for inserting records in a person table in my DB

System.IO.MemoryStream ms = new System.IO.MemoryStream();
                Image img = Image_Box.Image;
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                this.personTableAdapter1.Insert(NIC_Box.Text.Trim(), Application_Box.Text.Trim(), Name_Box.Text.Trim(), Father_Name_Box.Text.Trim(), DOB_TimePicker.Value.Date, Address_Box.Text.Trim(), City_Box.Text.Trim(), Country_Box.Text.Trim(), ms.GetBuffer());

but when i retrieve this with this code

    byte[] image = (byte[])Person_On_Application.Rows[0][8];
                        MemoryStream Stream = new MemoryStream();
                        Stream.Write(image, 0, image.Length);
                        Bitmap Display_Picture = new Bitmap(Stream);

Image_Box.Image = Display_Picture;

it works perfectly fine but if i update this with my own generated Query like

System.IO.MemoryStream ms = new System.IO.MemoryStream();
                Image img = Image_Box.Image;
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                Query = "UPDATE Person SET Person_Image ='"+ms.GetBuffer()+"'  WHERE (Person_NIC = '"+NIC_Box.Text.Trim()+"')";

the next time i use the same code for retrieving the image and displaying it as used above . Program throws an exception

alt text http://www.freeimagehosting.net/image.php?3bb5f0d4b3.jpg][img]http://www.freeimagehosting.net/uploads/th.3bb5f0d4b3.jpg

So can any one tell me why i can't figure it out.

Query = "UPDATE Person SET Person_Image =@pic  WHERE (Person_NIC = '" + NIC_Box.Text.Trim() + "')";
                    SqlCommand cmd = new SqlCommand(Query);
                    SqlParameter picparameter = new SqlParameter();
                    picparameter.SqlDbType = SqlDbType.Image;
                    picparameter.ParameterName = "pic";
                    picparameter.Value = ms.GetBuffer();
                    cmd.Parameters.Add(picparameter);

                    db.ExecuteSQL(Query);

This thing worked with this code hurray lolz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM