其实很简单,可是在找到方法之前,网上到处搜索,各种说法一度以为很麻烦。所以记载下来分享。
以Access2007为例,创建数据库,建个表,要插入二进制数据的字段的数据格式设为OLE对象。
连接:
OleDbConnection aConnection;
String strConnect = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=e:\\userdata.accdb";
//视数据库类型和版本的不同,填写不同的Provider(引擎)。
aConnection = new OleDbConnection(strConnect);
aConnection.Open();
存入:
byte[] arrImage = ImageAndBytes.GetBytes(Image.FromFile("E:\\U38.jpg"));//ImageAndBytes是自写的图片与字节数组互转的类。
String strSql = String.Format("insert into [userdata]([strID],[Image]) values('ID001',:logo)");
OleDbCommand aCommand = new OleDbCommand(strSql, aConnection);
aCommand.Parameters.AddWithValue(":logo", arrImage);//带参数的命令
aCommand.ExecuteNonQuery();
读取:
OleDbCommand bCommand = new OleDbCommand("select Image from userdata where strID=ID001", aConnection);
//保证选出来的第一行第一列就是你要的数据。
byte[] bytes = (byte[])bCommand.ExecuteScalar();
Image img = ImageAndBytes.GetImage(bytes);
pictureBox1.Image = img;