讀取Access 檔案資料 by Oledb
最近花了我數小時的時間,在網路世界裡,讓我看到一些不凡的高手,留下一些很棒的程式,
我將內容留下來,做為我的參考,怕未來這些網站消失,就看不到那麼好的程式
資料來源 : https://social.msdn.microsoft.com/Forums/windows/en-US/98d68c15-b28c-4f3e-92d7-e5b4aa6c2554/how-to-load-image-from-acces-database-and-put-it-in-picturebox-c?forum=winformsdatacontrols

Then the code to save the picture to database:
private void button1_Click(object sender, EventArgs e)
{
string fileName = @"D:\Pictures\Pic.PNG";
string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Documents\Database1.accdb";
FileInfo fi = new FileInfo(fileName);
using (FileStream fs = fi.OpenRead())
{
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
using (OleDbConnection cn = new OleDbConnection(strConn))
{
cn.Open();
using (OleDbCommand cm = new OleDbCommand())
{
cm.Connection = cn;
cm.CommandType = CommandType.Text;
cm.CommandText = "insert into Table3 (Img) values(@file)";
OleDbParameter spFile = new OleDbParameter("@file", SqlDbType.Image);
spFile.Value = bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery();
MessageBox.Show("Saved successfully");
}
}
}
}
Then the code to load it from database to PictureBox:
DataSet ds = new DataSet();
private void showImage(int index)
{
byte[] bytes = (byte[])ds.Tables[0].Rows[index][1];
MemoryStream memStream = new MemoryStream(bytes);
try
{
Bitmap myImage = new Bitmap(memStream);
pictureBox1.Image = myImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
pictureBox1.Image = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Documents\Database1.accdb";
using (OleDbConnection cnn = new OleDbConnection(strConn))
{
cnn.Open();
using (OleDbDataAdapter da = new OleDbDataAdapter("select * from Table3", cnn))
{
da.Fill(ds);
Random ran = new Random();
int index = ran.Next(ds.Tables[0].Rows.Count);
showImage(index);
}
}
}
Sure, also you can use OpenFileDialog control to let use choose the file from his computer:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Choose:";
openFileDialog1.Filter = "All file(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Documents\Database1.accdb";
//...
}
}