1.创建表:
drop table if exists photo;
CREATE TABLE photo (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) COMMENT '名称',    photo blob COMMENT '照片')
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_general_ci;

图片在MySql中的数据存储格式为blob类型;Blob是一个可以存储二进制文件的容器。

2.编写图片流数据存取的工具类:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {
    private static File file = null;

/**
     * 从本地文件读取图像的二进制流
     *
     * @param infile
     * @return
     */
    public static FileInputStream getImageByte(String infile) {
        FileInputStream imageByte = null;
        file = new File(infile);
        try {
            imageByte = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return imageByte;
    }

/**
     * 将图片流读出为图片
     *
     * @param inputStream
     * @param path
     */
    public static void readBlob(InputStream inputStream, String path) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

}
}

3.将本地文件保存到数据库

  需要添加MySql的数据库驱动--mysql-connector-java-5.1.24-bin.jar

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ImageInsert {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String user = "root";
        String password = "root";
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        PreparedStatement preparedStatement = null;
        InputStream inputStream = null;
        inputStream = ImageUtil.getImageByte("D:\\temp\\photo1.png");
        try {
            String sql = "insert into photo(id,name,photo) values(?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);
            preparedStatement.setString(2, "朱莉");
            preparedStatement.setBinaryStream(3, inputStream,
                    inputStream.available());
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (preparedStatement != null)
                        preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

}
}

4.从数据库中读取并生成图片

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ImageGet {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String user = "root";
        String password = "root";
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Statement statement = null;
        ResultSet resultSet = null;
        InputStream inputStream = null;
        try {
            statement = connection.createStatement();
            String sql = "select p.photo from photo p where id = 1";
            resultSet = statement.executeQuery(sql);
            resultSet.next();
            inputStream = resultSet.getBinaryStream("photo");
            ImageUtil.readBlob(inputStream, "D:\\temp\\photo2.png");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (resultSet != null)
                        resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    if (statement != null)
                        if (statement != null)
                            try {
                                statement.close();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            } finally {
                                if (connection != null)
                                    try {
                                        connection.close();
                                    } catch (SQLException e) {
                                        e.printStackTrace();
                                    }
                            }
                }
            }
        }

}
}

Java+MySql图片数据保存与读取的具体实例的更多相关文章

  1. Java+MySql图片数据保存

    之前一直没有做过涉及到图片存储的应用,最近要做的东东涉及到了这个点,就做了一个小的例子算是对图片存储的初试吧! 1.创建表: drop table if exists photo; CREATE TA ...

  2. C# 结构体和List<T>类型数据转Json数据保存和读取

    C#  结构体和List<T>类型数据转Json数据保存和读取 一.结构体转Json public struct FaceLibrary { public string face_name ...

  3. Numpy之数据保存与读取

      在pandas使用的25个技巧中介绍了几个常用的Pandas的使用技巧,不少技巧在机器学习和深度学习方面很有用处.本文将会介绍Numpy在数据保存和读取方面的内容,这些在机器学习和深度学习方向也大 ...

  4. java大并发数据保存方案

    做了几年.net,如今终于要做java了. 需求: 线下终端会定时上传gps位置到服务端,服务端收到数据保存到mysql数据库,当线下终端过多时,问题出现了,首当其冲的是数据库连接池经常会崩溃,单个t ...

  5. //NSUserDeafult 图片的保存与读取

    //NSUserDeafult保存图片数据到本地 -(void)saveImage:(UIImage *)image{ NSData* data=[NSKeyedArchiver archivedDa ...

  6. java+Mysql大数据的一些优化技巧

    众所周知,java在处理数据量比较大的时候,加载到内存必然会导致内存溢出,而在一些数据处理中我们不得不去处理海量数据,在做数据处理中,我们常见的手段是分解,压缩,并行,临时文件等方法; 例如,我们要将 ...

  7. as3+java+mysql(mybatis) 数据自动工具(四)

    现在介绍一下只配置 as3 与 java 公用的数据类,这种配置一般是该数据类只需要在 as3 与 java 之间转换,跟数据库没有关系.比如在客户端与服务端的数据交换中,需要定义一个统一返回请求的数 ...

  8. java mysql大数据量批量插入与流式读取分析

    总结下这周帮助客户解决报表生成操作的mysql 驱动的使用上的一些问题,与解决方案.由于生成报表逻辑要从数据库读取大量数据并在内存中加工处理后在 生成大量的汇总数据然后写入到数据库.基本流程是 读取- ...

  9. as3+java+mysql(mybatis) 数据自动工具(七) - 完结

    autoscript packed 文件地址:http://pan.baidu.com/s/1dDvgcO5 如果需要项目源码的话,可以留下邮箱,先声明一下,该工具主要是为了实现自动同步输出代码类文件 ...

随机推荐

  1. Ubuntu 安装 Xfce4 桌面

    sudo apt-get install xubuntu-desktop From: http://tieba.baidu.com/p/294762291

  2. Linux 使用 su 切换用户提示 Authentication Failure 的解决方法

    Ubuntu v14.04,使用 su 命令切换用户时报验证失败的错误 这个问题产生的原因是由于 ubuntu 系统默认是没有激活 root 用户的,需要我们手工进行操作,在命令行界面下,或者在终端中 ...

  3. oracle PL/SQL管理命令语句

    一.ORACLE的启动和关闭 1.在单机环境下 要想启动或关闭ORACLE系统必须首先切换到ORACLE用户,如下 su - oracle a.启动ORACLE系统 oracle>svrmgrl ...

  4. XML操作总结

    在开发过程中对XML的使用不是太多,要用到时候也是想办法绕过去,最近一个同事给了一个详细的操作.分享一下 using System; using System.Collections.Generic; ...

  5. display:inline-block左右元素上下不对齐

    今天做了两个inline-block元素,出现左右两个元素顶端出现上下不对齐的情况(下图): 解决办法: 把应用 inline-block的元素加上 vertical-align: top; .CSS ...

  6. Ms sql pivot unpivot

    --建表 create table dbo.orders ( orderid int not null primary key nonclustered, orderdate datetime not ...

  7. 第九十七天请假 PHP TP框架 MVC模式

    MVC : M->Model 模型(数据层)     V->View 视图(视图层)  C->Controller 控制器(逻辑层)            M : 操作数据(连接数据 ...

  8. JavaScript(复习总结)

    一.三个常用对话框 1.alert(""):警告对话框,作用是弹出一个警告对话框(最常用) 2.confirm(""):确定对话框,弹出一个带确定和取消按钮的对 ...

  9. Python str方法总结

    1.返回第一个字母大写 S.capitalize(...) S.capitalize() -> string 1 2 3 4 >>>a = 'shaw' >>> ...

  10. 【python】密码生成器

    #!/usr/bin/env python#-*- coding:UTF-8 -*- import random   #导入random模块import string  #导入string模块 sal ...