My code for inserting image in database is as follows:
MemoryStream ms =new MemoryStream();
byte[] PhotoByte=null;
PhotoByte=ms.ToArray();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
PhotoByte =ms.ToArray();
Str = "insert into Experimmm Values('" + PhotoByte + "','" + textBox1.Text + "')";
Conn.Open();
cmd.Connection = Conn;
cmd.CommandText = Str;
cmd.ExecuteNonQuery();
Conn.Close();
Which is going well. I can see binary data in ma database table like <Binary Data>
My code for retrieving data is:
Str ="select * from Experimmm where id = '" +textBox2.Text + "'";
Conn.Open();
cmd.Connection = Conn;
cmd.CommandText = Str;
dr = cmd.ExecuteReader();
if (dr.Read())
{ label1.Text = dr.GetValue(1).ToString();
byte[] PhotoByte = (byte[])dr.GetValue(0);
MemoryStream mem = new MemoryStream(PhotoByte, 0, PhotoByte.Length);
//but an error takes place on next line "Parameter is not valid."
pictureBox2.Image = Image.FromStream(mem);
} Conn.Close();
I'm using visual studio 10 , C# ,sql server 2005
You should be using a parameterized query instead of concatenating a SQL string.
Apart from fixing the obvious SQL Injection vulnerability, this will enable you to properly insert an image into the database.
There are many questions and answers on how to insert into a SQL Server image/binary field - you should look at them.
It is possible of course to store your images in db. However it is not recommended. It is better to store them in a file system.
Your code is a bit messy. The following is a better example.
When you retrieve you could use a binary writer in some handler
You have several issues with your code. I'll address it line-by-line:
While it's not a problem, you have needless assignments here. The code above could be more clearly written this way:
Next, the following code is not using parameters. Always, always, ALWAYS parameterize your SQL queries instead of dynamically building the SQL. No, seriously, always. Yes, even then. (Also, what is the
Str
variable? Some sort of reused instance variable? Don't do that.)Instead, it should be this:
Next, we'll move onto your retrieval. Again with the
Str
variable, don't do this sort of thing. Also, you need to parameterize this query as well.