我要感谢所有在上一个问题中提供帮助的人。 但是现在,我对另一个语句 saveimageto MS access 有疑问。 首先请问,在ms access数据库上,Datatype应该放附件吗?
我的代码:
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 (id,picture) values ('" + textBox1.Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
con.Close();
}
我使用 openFIledialog 将我的图片插入图片框。
最佳答案
首先,使用参数。永远不要为 SQL 命令连接字符串,因为它会向 SQL 注入(inject)开放。这是一个易于遵循的良好做法,可以避免您将来遇到很多麻烦。
也就是说,像这样的东西应该可以工作:
// You've got the filename from the result of your OpenDialog operation
var pic = File.ReadAllBytes(yourFileName);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 (id, picture) values (@p1, @p2)";
cmd.Parameters.AddWithValue("@p1", TextBox1.Text);
cmd.Parameters.AddWithValue("@p2", pic);
cmd.ExecuteNonQuery();
此处凭内存引用,但如果该代码给您带来麻烦,请告诉我。如果我没记错的话,类似的东西应该可以工作。
编辑。- 如果您在 PictureBox 控件上预加载图像,请将该图像转换为字节数组,然后将该字节数组用作第二个参数。
编辑 (2).- 一点澄清。如果您要从文件中获取图像,那么您就有它的路径;然后你可以使用 File.ReadAllBytes(string path)
。在我的示例中,我假设 yourFileName
是成功执行 OpenDialog
操作后所选文件的文件名和路径名。所以你可以像这样使用它:
byte[] fromPath = File.ReadAllBytes(@"C:\walls\aurora.jpg");
然后您将图像存储到字节数组 fromPath 中,转换为字节并准备好在插入命令中使用,如上所示。
但是如果您从图片框控件中获取图像,情况就会有所不同:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, Imaging.ImageFormat.Jpeg);
byte[] fromControl = ms.GetBuffer();
在那个例子中,我创建了一个MemoryStream
,用图片框控件的内容填充它,然后将它传递给字节数组,我们再次准备好将它用作参数用于我们的插入查询。
哦,别忘了补充
using System.IO;
using System.Drawing;
您的使用。
关于C# 插入图片到Ms Access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15273617/