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. Codeforces 723c [贪心][乱搞]

    /* 不要低头,不要放弃,不要气馁,不要慌张. 题意: 给一个n和m. 第二行给n个数. 每次操作可以把n个数中的任何一个数替代为别的数,问最少的操作次数使得1.2.3.4.5...m中的数出现的次数 ...

  2. (medium)LeetCode 278.First Bad Version

    You are a product manager and currently leading a team to develop a new product. Unfortunately, the ...

  3. JAVA设计模式之门面模式

    在阎宏博士的<JAVA与模式>一书中开头是这样描述门面(Facade)模式的: 门面模式是对象的结构模式,外部与一个子系统的通信必须通过一个统一的门面对象进行.门面模式提供一个高层次的接口 ...

  4. NandFlash读写

    1.NandFlash分类 根据物理结构上的区别,NandFlash主要分为如下两类:•SLC (Single Level Cell): 单层式存储•MLC (Multi Level Cell): 多 ...

  5. js显示当前时间

    闲着没事在闪存里看到有人需要js显示当前时间,就一时兴起写了个. 输出格式:“2013年12月18日 星期三 上午9:05:00 ”. <script type="text/javas ...

  6. mybatis关联查询,一对一,一对多

    注:这篇文章的代码有部分删减,不能直接使用,不过关键代码都存在  应用场景: 想用mybatis做关联查询,并且把查询出的数据自动组装成对象可以使用关联查询. 1.一对一实现 例如:一部小说,属于一个 ...

  7. [转] Making GTFS query more convenient

    url:http://ontrakinfo.wordpress.com/2012/10/29/making-gtfs-query-more-convenient/ 这简直说出了我的心声. I have ...

  8. 更改form字段内容颜色

    1.fnd_global.Newline ---换行2.设置栏位值颜色:POST-QUERY SET_ITEM_INSTANCE_PROPERTY('FIND_RESULT.STATUS',CURRE ...

  9. JDBC中如何获取SUM函数返回的结果

    代码如下: ResultSet rs = stmt.executeQuery("SELECT sum() from...."); int keyValue = -1; if (rs ...

  10. Python在安装第三方模块遇到的问题及解决办法

    今天在安装第一个模块psutil的时候出现了以下问题: 1.找不到Python.h文件 解决办法:重新安装python环境:sudo apt-get install python-dev 说明:网上有 ...