C#Access中OLE对象的操作有时候需要⼤数据的存取时,如图⽚,需要⽤到ole对象的操作。
⾸先,在默认⽂件中,添加两个名空间
using System.Data.OleDb;
using System.IO;
⼀个⽤于数据库操作,⼀个⽤于⼆进制⽂件操作
在Access中新建数据库Database1.mdb, 完整⽂件路径D:\Documents\Database1.mdb
写⼊OLE对象数据
打开⽂件,选择⼀个⼤的图像⽂件,然后存⼊数据库。
代码如下:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
Byte[] buff = new Byte[fs.Length];
BinaryReader rd = new BinaryReader(fs);
rd.Read(buff, 0, Convert.ToInt32(fs.Length));
OleDbCommand command = new OleDbCommand("INSERT INTO 表1 ([object], path) VALUES(@object, @path)", conn);
command.Parameters.Add("@object", OleDbType.Binary, buff.Length).Value = buff;
command.Parameters.Add("@path", OleDbType.Char, 255).Value = openFileDialog1.FileName;
command.ExecuteNonQuery();
rd.Close();
fs.Close();
}
}
读出OLE对象数据按钮
将数据库⾥存进的图⽚⽂件⼀个个读出来,另存为临时⽂件testfile*.png(测试⽤的⽂件都是png图⽚)
代码如下:
OleDbCommand command = new OleDbCommand("SELECT [object], path FROM 表1", conn);
OleDbDataReader dr = command.ExecuteReader();
FileStream fs;
BinaryWriter writer;
int bufferSize = 100;
byte[] outByte = new byte[bufferSize];
int i=0;
while (dr.Read())
{
string filename = "D:\\documents\\testfile"+ i.ToString() + ".png";
fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
writer = new BinaryWriter(fs);对象图片高清
int startIndex = 0;
long retval = dr.GetBytes(0, startIndex, outByte, 0, bufferSize);
while (retval == bufferSize)
{
writer.Write(outByte);
writer.Flush();
startIndex += bufferSize;
retval = dr.GetBytes(0, startIndex, outByte, 0, bufferSize);
}
writer.Write(outByte, 0, (int)retval - 1);
writer.Flush();
writer.Close();
fs.Close();
i++;
}
dr.Close();
}
此外,注意使⽤数据库前,先要打开数据库,⽤完关闭。
相关代码⽚段1:
OleDbConnection conn;
public Form1()
{
InitializeComponent();
conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=d:\Documents\Database1.mdb"; conn.Open();
}
⽚段2:
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
conn.Close();
}
⾄此,OLE对象存取学习实践完毕,代码也已完整。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论