C# Access中OLE对象的操作
有时候需要大数据的存取时,如图片,需要用到ole对象的操作。
首先,在默认文件中,添加两个名空间
using System.Data.OleDb;
using System.IO;
一个用于数据库操作,一个用于二进制文件操作
在Access中新建数据库Database1.mdb, 完整文件路径D:\Documents\Database1.mdb
写入OLE对象数据
打开文件,选择一个大的图像文件,然后存入数据库。
代码如下:
private void button1_Click(object sender, EventArgs e)
{
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图片)
代码如下:
private void button2_Click(object sender, EventArgs e)
{
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对象存取学习实践完毕,代码也已完整。
posted on 2017-09-14 14:36 不忘初心,知耻后勇 阅读(2388) 评论(0) 编辑 收藏 举报