将图像存储在数据库中并进行检索
本文关键字:检索 数据库 图像 存储 | 更新日期: 2023-09-27 18:22:06
我在数据库中插入图像的代码如下:
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
您的代码有几个问题。我会一行一行地解决:
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));
当然可以将图像存储在数据库中。但不建议使用。最好将它们存储在文件系统中。
你的代码有点乱。下面是一个更好的例子。
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; }
}
}
}
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();
}
您应该使用参数化查询,而不是连接SQL字符串。
除了修复明显的SQL注入漏洞外,这将使您能够正确地将映像插入数据库。
关于如何插入SQL Server映像/二进制字段,有很多问题和答案——您应该看看它们。