MySQL数据库之插入显示图片

     图书馆系统项目需要用到好多图片,并且要求存入到数据库中,对这个特别感兴趣,于是上网查了资料,采用C#语言,进行了具体实现。


说明:

    功能:往MySQL数据库插入并显示图片;

    验证:执行插入功能后,我把该图片进行了本地的删除,然后执行显示功能,可以显示出来。

    数据库该字段类型:longblob

  • 原型部分

 

  • 数据库



  • 引用部分

 

/*
 * 作者:周丽同
 * 功能:简单实现往MySQL数据库插入显示图片;
 * 日期:2016年6月1日11:32:35
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Drawing.Imaging;

  • 窗体加载部分

 

        private void Form1_Load(object sender, EventArgs e)
        {
            //获取当前窗体上的picturebox1里面的路径内容或者URL;
            bool flag;
            flag = ImageWrite(pictureBox1.ImageLocation);
            //显示数据库里面存储的图片;
            pictureBox2.Image = MapSearchQuery();
        }

  • 往MySQL数据库插入图片代码

 

/// <summary>
        /// 将图片存入到数据库中
        /// </summary>
        /// <param name="strImagePath"></param>
        /// <returns></returns>
        public bool ImageWrite(string strImagePath)
        {
            //FileStream文件流;此部分需要引用:System.IO;
            FileStream fs = new System.IO.FileStream(strImagePath, FileMode.Open, FileAccess.Read);

            //获得图片字节数组
            byte[] byImage = new byte[fs.Length];
            fs.Read(byImage, 0, byImage.Length);
            fs.Close();

            //数据库连接
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = "Server=localhost;uid=root;password=1;Database=librarysystem;";

            //打开关闭连接
            try
            {
                conn.Open();
            }
            catch
            {
                conn.Close();
                conn.Dispose();
                throw new ArgumentException("检索失败啦!");
            }

            //判断数据库中内部有无记录
            MySqlCommand cmd1 = new MySqlCommand();
            //根据条件查询是否存在图片
            string strQueryCmd = "select * from t_picture";
            MySqlCommand cmdQuery = new MySqlCommand(strQueryCmd, conn);
            MySqlDataReader dataReader = cmdQuery.ExecuteReader();
            bool flag1 = dataReader.Read();
            //关闭连接
            cmd1.Dispose();
            conn.Close();
            conn.Dispose();


            //此处如果涉及到两次对数据库的访问,一定要记得关闭上次的连接,然后再进行接下来对数据库的操作;
            try
            {
                conn.Open();
            }
            catch
            {
                conn.Close();
                conn.Dispose();
                throw new ArgumentException("检索失败啦!");
            }
            //执行更新或插入操作操作
            MySqlCommand cmd = new MySqlCommand();
            if (flag1)    //flag1是上面操心操作的结果
            {
                cmd.CommandText = "update t_picture set picture=@picture";
            }
            else
            {
                cmd.CommandText = "insert into t_picture(picture) values (@picture)";
            }

            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@picture", MySqlDbType.LongBlob);
            cmd.Parameters[0].Value = byImage;
            cmd.Connection = conn;

            int affecteRows = 0;//初始化数据库操作的结果;
            try
            {
                affecteRows = cmd.ExecuteNonQuery();//返回对数据库的执行结果;
            }
            catch
            {
                affecteRows  = -1;
            }

            //关闭连接等
            cmd.Dispose();
            conn.Close();
            conn.Dispose();

            if (affecteRows <= 0)
            {
                MessageBox.Show("保存失败!");
                return false;
            }
            else
            {
                MessageBox.Show("保存成功!");
                return true;
            }
        }

  • 查询MySQL数据库存储的图片,并显示代码

/// <summary>
        /// 对MySQL数据库图片进行显示
        /// </summary>
        /// <returns></returns>
        public Image   MapSearchQuery()
        {
            //声明图片数组
             byte[] imageByteResulet;
            imageByteResulet = null;

            //连接数据库
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = "Server=localhost;Uid=root;Password=1;Database=librarysystem;";
            //对数据库进行开关闭
            try
            {
                conn.Open();
            }
            catch
            {
                conn.Close();
                conn.Dispose();
                throw new ArgumentException("图片加载超时啦!");
            }
            //执行查询操作(可以根据具体条件下的图片进行查询显示)
            string strQueryCmd = "select * from t_picture";
            MySqlCommand cmd = new MySqlCommand(strQueryCmd, conn);
            MySqlDataReader dataReader = null;
            try
            {
                dataReader = cmd.ExecuteReader();
            }
            catch
            {
                dataReader.Dispose();
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
                throw new ArgumentException("图片加载超时啦!");
            }

            //声明接收返回值图片
            Image imageResulet;
            if (dataReader.Read())
            {
                //获取数据库中图片字节数组
                imageByteResulet = new byte[dataReader.GetBytes(0, 0, null, 0, int.MaxValue)];
                dataReader.GetBytes(0, 0, imageByteResulet, 0, imageByteResulet.Length);

                //// 将图片字节数组加载入到缓冲流
                byte[] imageByte = imageByteResulet;
                MemoryStream imageStream = new MemoryStream(imageByte);

                ////从缓冲流生成图片
                imageResulet = Image.FromStream(imageStream, true);
                return imageResulet;
            }
            else
            {
                imageResulet = null;
            }

            dataReader.Dispose();
            cmd.Dispose();
            conn.Close();
            conn.Dispose();

            return imageResulet;
        }

    个人感觉这个方法不是最简单的,希望路过的大神,提出宝贵意见。


感谢您的宝贵时间···

原文地址:https://www.cnblogs.com/zhoulitong/p/6412385.html