using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication1 {
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK) {
label1.Text = ofd.FileName; this.pictureBox1.Image = Image.FromFile(label1.Text);
}
}
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/student.mdb");
DataSet ds = new DataSet();
private void button2_Click(object sender, EventArgs e) {
FileStream fs = new FileStream(label1.Text, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
OleDbCommand command = new OleDbCommand();
command.CommandText = "insert into pictureTab values(@id,@picture)";
command.Parameters.AddWithValue("@id", textBox1.Text);
command.Parameters.AddWithValue("@picture", data);
command.Connection = conn;
try {
conn.Open(); int i = command.ExecuteNonQuery();
} catch (Exception ex) {
MessageBox.Show(ex.ToString());
} finally {
conn.Close();
command = null;
}
}
private void button3_Click(object sender, EventArgs e) {
OleDbCommand command = new OleDbCommand(); command.CommandText = "select picture from pictureTab where (id = @id)";
command.Parameters.AddWithValue("@id", textBox1.Text);
command.Connection = conn;
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
try {
//ds = new DataSet(); conn.Open(); adapter.Fill(ds, "picture");
} catch (Exception ex) {
MessageBox.Show(ex.ToString());
} finally {
conn.Close();
command = null;
adapter = null;
}
byte[] data = (byte[])ds.Tables["picture"].Rows[0]["picture"];
using (MemoryStream memStream = new MemoryStream(data)) {
this.pictureBox1.Image = Image.FromStream(memStream);
ds.Tables.Clear();
}
}
}
}
/*
int id = int.Parse(textBox1.Text);
command = new OleDbCommand();
command.CommandText = "select picture from ?? where(id=@id)";
command.Parameters.AddWithValue("@id", id);
command.Connection = conn; conn.Open();
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
byte[] data = (byte[])reader["picture"];
MemoryStream mem = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(mem);
conn.Close();
*/
利用C#从Access数据库中存取图片
于 2011-04-24 13:42:00 首次发布