插入:picPath是图片的路径
try { //把照片通过流的方式读取到字节数组中! FileStream fs = File.OpenRead(picPath); byte[] b =newbyte[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("保存成功!"); } catch (Exception ex) { MessageBox.Show(ex.Message); }
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("保存成功!"); } catch (Exception ex) { MessageBox.Show(ex.Message); }
读取:
try { 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); } else { MessageBox.Show("未找到内容!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); }
con.Open(); byte[] b = (byte[])cmd.ExecuteScalar(); con.Close();
if (b !=null) { MemoryStream ms =new MemoryStream(b); pictureBox1.Image = Image.FromStream(ms); } else { MessageBox.Show("未找到内容!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); }