My code for inserting image in database is as follows:
MemoryStream ms =new MemoryStream();
byte[] PhotoByte=null;
PhotoByte=ms.ToArray();
pictureBox1.Image.Save
You have several issues with your code. I'll address it line-by-line:
MemoryStream ms =new MemoryStream();
byte[] PhotoByte=null;
PhotoByte=ms.ToArray();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
PhotoByte =ms.ToArray();
While it's not a problem, you have needless assignments here. The code above could be more clearly written this way:
MemoryStream ms =new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] PhotoByte =ms.ToArray();
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.)
Str = "insert into Experimmm Values('" + PhotoByte + "','" + textBox1.Text + "')";
Conn.Open();
cmd.Connection = Conn;
cmd.CommandText = Str;
cmd.ExecuteNonQuery();
Conn.Close();
Instead, it should be this:
Conn.Open();
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "insert into Experimmm (column list) values(@data, @name)";
cmd.Parameters.Add("@data", SqlDbType.VarBinary).Value = PhotoByte;
cmd.Parameters.Add("@name", SqlDbType.VarChar, yourlength).Value = textBox1.Text;
cmd.ExecuteNonQuery();
}
Conn.Close();
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.
byte[] data;
string name;
Conn.Open();
using(SqlCommand cmd = Conn.CreateCommand())
{
cmd.CommandText = "select column_list from Experimmm where id = @id";
cmd.Parameters.Add("@id", SqlDbType.VarChar, field_length).Value = textBox2.Text;
using(SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
data = (byte[])dr.GetValue(0);
name = (string)dr.GetValue(1);
}
}
}
Conn.Close();
label1.Text = name;
pictureBox2.Image = Image.FromStream(new MemoryStream(data));