ACCESS的Ole对象读取写入

Ole对象在Access中存储为二进制文件,读取的时候需要注意转换出的文件的编码格式

 1OleDbConnection OleConn = new OleDbConnection();
 2OleConn.ConnectionString =
@"
Provider=Microsoft.Jet.OleDb.4.0;data source=D:\WorkStation\Dialy_Sol\Dialy\Dialy.mdb";
 3OleDbCommand OleCmd = new OleDbCommand();
 4OleCmd.Connection = OleConn;
 5OleCmd.CommandType = CommandType.Text;
 6OleCmd.CommandText =
"
SELECT Dialy_Content FROM Dialy_Info WHERE Dialy_Date='2008-5-2'";
 7if (OleConn.State == ConnectionState.Closed)
 8{
 9OleConn.Open();
10}

11string DialyContent = "";
12byte[] Buff = new byte[1000];
13OleDbDataReader OleReader = OleCmd.ExecuteReader();
14while (OleReader.Read())
15{
16OleReader.GetBytes(00, Buff, 01000);
17DialyContent += Encoding.Unicode.GetString(Buff);
18}

< /span>19< span style="color: #000000;">
//DialyContent就是读取出来后的中文

---------------------------下面是读取写入的示例---------------------------------

******* OleDbConnection conn;
public Form1()
{
InitializeComponent();
conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=d:\Database1.mdb";
conn.Open();

}

//it is for storing a file into database
******* 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();

}

}

******* void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
conn.Close();
}
//it is for reading the data from the database and store it to a file
******* 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];
while(dr.Read())
{
string filename = dr.GetString(1);
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();

}
dr.Close();
}
 

posted @ 2010-02-15 12:02  猪悟能  阅读(2470)  评论(0编辑  收藏  举报