Java如何将BLOB数据存储到数据库中?
数据库BLOB(二进制大对象)可用于存储任何数据,例如可以是图像,音频或视频文件。本示例说明如何使用JDBC库将图像存储在数据库中。要将二进制信息发送到数据库,我们可以调用该PreparedStatement.setBinaryStream()方法并传递适当的输入流及其大小。
package org.nhooo.example.jdbc; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class BlobDemo { 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)) { conn.setAutoCommit(false); String sql = "INSERT INTO product_images " + "(product_id, name, description, image) VALUES (?, ?, ?, ?)"; String image = "/uml-distilled-3rd-edition.jpg"; try (PreparedStatement stmt = conn.prepareStatement(sql); InputStream is = BlobDemo.class.getResourceAsStream(image)) { stmt.setLong(1, 1L); stmt.setString(2, "uml-distilled-3rd-edition.jpg"); stmt.setString(3, "UML Distilled 3rd Edition"); stmt.setBinaryStream(4, is); stmt.execute(); conn.commit(); } catch (Exception e) { conn.rollback(); e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } } }
product_images表的结构。
CREATE 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依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>