Java mysql blob 数据读写操作

复制代码

package com.lw.database;

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

/**
 * CREATE: CREATE TABLE IDCard ( id char(18),pic BLOB);
 * @author fhadmin
 * from www.fhadmin.cn
 */
public class LOBTest {

    protected static final String DEFAULT_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
    protected static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
    
    private Connection connection = null;
    
    public LOBTest() throws ClassNotFoundException, SQLException {
        Class.forName(DRIVER_NAME);
        connection = DriverManager.getConnection(DEFAULT_URL, "user", "password");
    }
    
    public void insert(String id,String path) throws SQLException, IOException {
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO IDCard VALUES (?,?)");
        preparedStatement.setString(1, id);
        FileInputStream fileInputStream = new FileInputStream(path);
        preparedStatement.setBlob(2, fileInputStream,fileInputStream.available());
        preparedStatement.execute();
    }
    
    public void get(String id) throws SQLException, IOException {
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT pic FROM IDCard WHERE id = ?");
        preparedStatement.setString(1, id);
        ResultSet results = preparedStatement.executeQuery();
        while(results.next()) {
            FileOutputStream outputStream = new FileOutputStream("/Users/liuwei/temp.png");
            InputStream inputStream = results.getBinaryStream(1);
            int num = -1;
            while((num=inputStream.read())!=-1) {
                outputStream.write(num);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        }
    }
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
        LOBTest test = new LOBTest();
        test.insert("78907656784323", "/Users/liuwei/Documents/bt_next_nor.png");
        test.get("78907656784323");
    }
}

复制代码

注意:

  MySQL的sql教程四种BLOB类型 

    类java基础教程型  大小(单位:字节) 

      TinyBlob  最大 255B

        Blob  最大 65K 

        MediumBlob  最大 16M 

      LongBlob  最大 4G 

插入python基础教程图像的c#教程时候,注意下图像大小,图像超过该类vb.net教程型所能容纳的最大字节的时候,会报错

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值