图片存入数据库,用的Accesss, 类型OLE 对象。
保存图片到数据库public partial class frmMain : Form
{
//保存用户选择的照片
string picPath = string.Empty;
public frmMain()
{
InitializeComponent();
picPath = Path.Combine(Application.StartupPath, "default.jpg");
pictureBox1.Image = Image.FromFile(picPath);
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog flg = new OpenFileDialog();
flg.Filter = "*.jpg|*.jpg|*.bmp|*.bmp|*.gif|*.gif";
if (flg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(flg.FileName);
picPath = flg.FileName;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//把照片通过流的方式读取到字节数组中!
FileStream fs = File.OpenRead(picPath);
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
OleDbConnection con = new OleDbConnection(DB.connectionString);
OleDbCommand cmd = new OleDbCommand("INSERT INTO Test (title,pic) VALUES (@title,@pic)", con);
cmd.Parameters.Add("@title", OleDbType.VarChar).Value = txtTitle.Text;
cmd.Parameters.Add("@pic", OleDbType.Binary).Value = b;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("保存成功!");
}
读取图片 string sql = "select pic from Test where Id = @Id";
OleDbConnection con = new OleDbConnection(DB.connectionString);
OleDbCommand cmd = new OleDbCommand(sql,con);
cmd.Parameters.AddWithValue("@Id", txtId.Text);
con.Open();
byte[] b = (byte[])cmd.ExecuteScalar();
con.Close();
if (b != null)
{
MemoryStream ms = new MemoryStream(b);
pictureBox1.Image = Image.FromStream(ms);
}
这样通过对图片转换流操作把图片以byte类型存入数据库