加入收藏 | 设为首页 | 会员中心 | 我要投稿 海南站长网 (https://www.0898zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

将图片添加到mysql中的方案

发布时间:2022-02-22 19:44:55 所属栏目:MySql教程 来源:互联网
导读:小编给大家分享一下将图片添加到mysql中的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧! 如果要图片存进数据库 要将图片转化成二进制。 1.数据库存储图片的字段类型要为blob二进制大对象类型 2.将图片流转化为二进制 下面放上代码实
       小编给大家分享一下将图片添加到mysql中的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
  
       如果要图片存进数据库  要将图片转化成二进制。
 
1.数据库存储图片的字段类型要为blob二进制大对象类型
 
2.将图片流转化为二进制
 
下面放上代码实例
 
一、数据库
 
CREATE TABLE `photo` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `photo` blob,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
二、数据库链接
 
/**
 *
 */
package JdbcImgTest;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
/**
 * @author Administrator
 *
 */
public class DBUtil
{
    // 定义数据库连接参数
    public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
    
    public static final String URL = "jdbc:mysql://localhost:3306/test";
    
    public static final String USERNAME = "root";
    
    public static final String PASSWORD = "root";
    
    // 注册数据库驱动
    static
    {
        try
        {
            Class.forName(DRIVER_CLASS_NAME);
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("注册失败!");
            e.printStackTrace();
        }
    }
    
    // 获取连接
    public static Connection getConn() throws SQLException
    {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
    
    // 关闭连接
    public static void closeConn(Connection conn)
    {
        if (null != conn)
        {
            try
            {
                conn.close();
            }
            catch (SQLException e)
            {
                System.out.println("关闭连接失败!");
                e.printStackTrace();
            }
        }
    }
    
    //测试
/*    public static void main(String[] args) throws SQLException
    {
        System.out.println(DBUtil.getConn());
    }
    */
}
三、图片流
 
package JdbcImgTest;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
 
/**
 * @author Administrator
 *
 */
public class ImageUtil
{
    
    // 读取本地图片获取输入流
    public static FileInputStream readImage(String path) throws IOException
    {
        return new FileInputStream(new File(path));
    }
    
    // 读取表中图片获取输出流
    public static void readBin2Image(InputStream in, String targetPath)
    {
        File file = new File(targetPath);
        String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
        if (!file.exists())
        {
            new File(path).mkdir();
        }
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) != -1)
            {
                fos.write(buf, 0, len);
            }
            fos.flush();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != fos)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
四、转码存储
 
package JdbcImgTest;
 
/**
 * @author Administrator 测试写入数据库以及从数据库中读取
 */
public class ImageDemo
{
    
    // 将图片插入数据库
    public static void readImage2DB()
    {
        String path = "D:/Eclipse/eclipseWorkspace/TestProject/Img/mogen.jpg";
        Connection conn = null;
        PreparedStatement ps = null;
        FileInputStream in = null;
        try
        {
            in = ImageUtil.readImage(path);
            conn = DBUtil.getConn();
            String sql = "insert into photo (id,name,photo)values(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 1);
            ps.setString(2, "Tom");
            ps.setBinaryStream(3, in, in.available());
            int count = ps.executeUpdate();
            if (count > 0)
            {
                System.out.println("插入成功!");
            }
            else
            {
                System.out.println("插入失败!");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            DBUtil.closeConn(conn);
            if (null != ps)
            {
                try
                {
                    ps.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
        }
        
    }
    
    // 读取数据库中图片
    public static void readDB2Image()
    {
        String targetPath = "C:/Users/Jia/Desktop/mogen.jpg";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try
        {
            conn = DBUtil.getConn();
            String sql = "select * from photo where id =?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 1);
            rs = ps.executeQuery();
            while (rs.next())
            {
                InputStream in = rs.getBinaryStream("photo");
                ImageUtil.readBin2Image(in, targetPath);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            DBUtil.closeConn(conn);
            if (rs != null)
            {
                try
                {
                    rs.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            if (ps != null)
            {
                try
                {
                    ps.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            
        }
    }
    
    //测试
    public static void main(String[] args)
    {
        //readImage2DB();
        readDB2Image();
    }
}
看完了这篇文章,相信你对将图片添加到mysql中的方法有了一定的了解。

(编辑:海南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读