将图像存储在数据库中并检索它

时间:2012-01-30 19:42:27

标签: c# visual-studio-2010 sql-server-2005

我在数据库中插入图片的代码如下:

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();

哪个进展顺利。我可以在ma数据库表中查看二进制数据,如<Binary Data> 我检索数据的代码是:

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();

我正在使用visual studio 10,C#,sql server 2005

4 个答案:

答案 0 :(得分:5)

您的代码存在多个问题。我将逐行解决这个问题:

MemoryStream ms =new MemoryStream();
byte[] PhotoByte=null;
PhotoByte=ms.ToArray();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
PhotoByte =ms.ToArray();

虽然这不是问题,但你在这里做了不必要的任务。上面的代码可以用这种方式写得更清楚:

MemoryStream ms =new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] PhotoByte =ms.ToArray();

接下来,以下代码不使用参数。 始终,始终,始终参数化您的SQL查询,而不是动态构建SQL。不,认真,永远。是的,即便如此。(另外,Str变量是什么?某种重用的实例变量?不要这样做。)

Str = "insert into Experimmm Values('" + PhotoByte + "','" + textBox1.Text + "')";
Conn.Open();
cmd.Connection = Conn;
cmd.CommandText = Str;
cmd.ExecuteNonQuery();
Conn.Close();

相反,它应该是这样的:

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();

接下来,我们将继续您的检索。再次使用Str变量,不要做这种事情。此外,您还需要参数化此查询。

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));

答案 1 :(得分:2)

当然可以将您的图像存储在db中。但是不建议这样做。最好将它们存储在文件系统中。

你的代码有点乱。以下是一个更好的例子。

MemoryStream ms =new MemoryStream(); 
byte[] PhotoByte=null; 
pictureBox1.Image.Save(ms, ImageFormat.Jpeg); 
PhotoByte =ms.ToArray(); 
// I'm not sure whether you are able to create an sql by simply concating the string
Str = "insert into Experimmm Values('@PhotoBytes','@MyTextValue')"; 
// You have to parametrize your query
cmd.Parameters.AddWithValue("PhotoBytes", PhotoByte);
// This also helps you to avoid syntactical corruption in case of ' and sql injection
cmd.Parameters.AddWithValue("MyTextValue", textBox1.Text );
Conn.Open(); 
cmd.Connection = Conn; 
cmd.CommandText = Str; 
cmd.ExecuteNonQuery(); 
Conn.Close(); 

检索时,您可以在某个处理程序中使用二进制编写器

namespace TestNS
{
   public class MyHttpHandler : IHttpHandler
   {
      // Override the ProcessRequest method.
      public void ProcessRequest(HttpContext context)
      {
         // Your preparations, i.e. querystring or something
         var conn = new SqlConnection("Your connectionstring");
         var command = new SqlCommand("Your sql for retrieval of the bytes", conn);
         conn.Open();
         var data = (Byte[])command.ExecuteScalar();
         conn.Close();
         context.Response.BinaryWrite(data);      }

      public Boolean IsReusable
      {
         get { return false; }
      }
   }
}

答案 2 :(得分:1)

OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\KUTTY\Real_Project\Royalty_Pro\DbRoyalty_Access\Buzz_Loyalty.mdb");
DataSet ds = new DataSet();
con.Open();
OleDbCommand cmd = new OleDbCommand("select pic from test_table where id_image='123'",con);
OleDbDataAdapter da=new OleDbDataAdapter(cmd);
da.Fill(ds,"test_table");
//con.Close();

//ds = new DataSet();
//da.Fill(ds, "test_table");
FileStream FS1 = new FileStream("image.jpg", FileMode.Create);
if (ds.Tables["test_table"].Rows.Count > 0)
{
    byte[] blob = (byte[])ds.Tables["test_table"].Rows[0]["pic"];
    FS1.Write(blob, 0, blob.Length);
    FS1.Close();
    FS1 = null;

    byte[] imageData = (byte[])cmd.ExecuteScalar();
    MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length);
    pictureBox2.Image = Image.FromStream(ms);



    pictureBox2.Image = Image.FromFile("image.jpg");
    pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
    pictureBox2.Refresh();

    pictureBox2.Image = Image.FromStream(new MemoryStream(blob));  
    pictureBox2.Image = Image.FromFile("image.jpg");
    pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
    pictureBox2.Refresh();
}

答案 3 :(得分:0)

您应该使用parameterized query而不是连接SQL字符串。

除了修复明显的SQL Injection漏洞之外,这还可以让您将图像正确插入数据库。

how to insert into a SQL Server image/binary field上有很多问题和答案 - 你应该看看它们。