Java MySQL BLOB data read / write operation

FHAdmin 2022-06-24 07:08:29 阅读数:881

javamysqlblobdataread

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 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");
}
}

Be careful :

MySQL Four kinds of BLOB type

type size ( Company : byte )

TinyBlob Maximum 255B

Blob Maximum 65K

MediumBlob Maximum 16M

LongBlob Maximum 4G

When inserting an image , Note the image size , When the image exceeds the maximum bytes that the type can hold , Will report a mistake

copyright:author[FHAdmin],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/20210707145919677g.html