在 C# 中读取 SQL 中的图像错误
本文关键字:图像 错误 读取 SQL | 更新日期: 2023-09-27 18:33:04
我有一个SQLite数据库,我有一个名为BLOB类型的PersonalPic的字段
这是我将图像保存到SQLite的代码
cm.CommandText = "insert into People(Name,FullName,FatherName,MotherName,NationalID,Mobile,Phone,Birth,Intma,Info,Address,CuAddress,PersonalPic,Pics) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+dateTimePicker1.Value.ToString("yyyy-MM-dd")+"','"+textBox8.Text+"','"+textBox9.Text+"','"+textBox10.Text+"','"+textBox11.Text+"','"+ConvertToString(personalpic)+"','"+ConvertToString(pic)+"')";
cm.ExecuteNonQuery();
public string ConvertToString(String path)
{
FileStream fs = new FileStream(path,
FileMode.OpenOrCreate, FileAccess.Read);
byte[] rawData = new byte[fs.Length];
fs.Read(rawData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(rawData);
return base64String;
}
当我尝试检索图像时,它被保存没有问题,它给了我参数不是有效的异常
SQLiteDataReader reader = cm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
textBox1.Text = reader["Name"].ToString();
textBox2.Text = reader["FullName"].ToString();
textBox3.Text = reader["FatherName"].ToString();
textBox4.Text = reader["MotherName"].ToString();
textBox5.Text = reader["NationalID"].ToString();
textBox6.Text = reader["Mobile"].ToString();
textBox7.Text = reader["Phone"].ToString();
dateTimePicker1.Value = DateTime.Parse(reader["Birth"].ToString());
textBox8.Text = reader["Intma"].ToString();
textBox9.Text = reader["Info"].ToString();
byte[] photoarray = (byte[])reader["PersonalPic"];
MemoryStream ms = new MemoryStream(photoarray);
MessageBox.Show(photoarray.Length.ToString());
ms.Position = 0;
pictureBox1.Image = Image.FromStream(ms);
}
}
reader.Close();
异常在行中(pictureBox1.Image = Image.FromStream(ms))
请帮忙!!
除了可怕的sql注入插入语句之外,您还将图片byte
数组转换为B64 string
。而且你不会在另一边转换它。您正在将完整的垃圾数据传递到您的图片框。要么将其从 byte[]
-> B64 string
转换回来,然后将其解码回byte[]
..或者一开始就不要将其另存为 B64 string
将ConvertToString
替换为ConvertToBlob
public byte[] ConvertToBlob(String path)
{
FileStream fs = new FileStream(path,
FileMode.OpenOrCreate, FileAccess.Read);
byte[] rawData = new byte[fs.Length];
fs.Read(rawData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
return rawData;
}
并将原始数据 Byte[] 直接传递给 SQL 查询(需要将其重写为参数化查询)。