C#将图片插入Ms Access

C#将图片插入Ms Access,c#,database,image,insert,C#,Database,Image,Insert,我要感谢所有在最后一个问题上给予帮助的人。 但现在,我对另一个语句有问题,它是saveimagetomsaccess。 首先,我想问一下,在ms access数据库上,数据类型应该放附件吗 我的代码: private void button2_Click(object sender, EventArgs e) { OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = Co

我要感谢所有在最后一个问题上给予帮助的人。 但现在,我对另一个语句有问题,它是saveimagetomsaccess。 首先,我想问一下,在ms access数据库上,数据类型应该放附件吗

我的代码:

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将图片插入picturebox。

首先,使用参数。永远不要为SQL命令指定字符串,因为它会向SQL注入打开自身。这是一个易于遵循的良好实践,可以避免您在将来遇到很多麻烦

这就是说,类似这样的方法应该有效:

// 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(字符串路径)
。在我的示例中,我假设
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();
在那个例子中,我创建了一个
内存流
,用picturebox控件的内容填充它,然后将它传递给字节数组,我们再次准备将它用作插入查询的参数

哦,别忘了加上

using System.IO;
using System.Drawing;

感谢你的使用

嗨,谭俊凯,你能说明问题是什么吗?你好,你的文件名是什么意思?您是否有teamviewer,这样我可以更轻松地问您。?var pic=File.ReadAllBytes(pictureBox1);可以这样使用吗?