文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>在数据库读取二进制文件

在数据库读取二进制文件

时间:2010-10-08  来源:Diose

图片存入数据库,用的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类型存入数据库

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载