java从数据库blob去读_Java如何从数据库读取BLOB数据?

本示例说明如何从数据库表读取BLOB数据。package org.nhooo.example.jdbc;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.sql.*;

public class BlobReadDemo {

private static final String URL = "jdbc:mysql://localhost/nhooo";

private static final String USERNAME = "root";

private static final String PASSWORD = "";

public static void main(String[] args) {

try (Connection conn =

DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

String sql = "SELECT name, image FROM product_images";

PreparedStatement stmt = conn.prepareStatement(sql);

ResultSet rs = stmt.executeQuery();

while (rs.next()) {

String name = rs.getString("name");

File image = new File(name);

try (FileOutputStream fos = new FileOutputStream(image)) {

byte[] buffer = new byte[1024];

// 获取我们的BLOB数据的二进制流

InputStream is = rs.getBinaryStream("image");

while (is.read(buffer) > 0) {

fos.write(buffer);

}

} catch (IOException e) {

e.printStackTrace();

}

}

} catch (SQLException e) {

e.printStackTrace();

}

}

}

表结构 product_imagesCREATE TABLE `product_images` (

`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,

`product_id` bigint(20) unsigned NOT NULL,

`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,

`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,

`image` blob,

PRIMARY KEY (`id`),

KEY `product_id` (`product_id`),

CONSTRAINT `product_images_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)

) ENGINE=InnoDB;

Maven依赖

mysql

mysql-connector-java

8.0.17

mysql-connector-java.svg?label=Maven%20Central


版权声明:本文为weixin_32380501原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。