将字节数组作为图像或文件从 Java 写入 MySQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17672829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:37:50  来源:igfitidea点击:

Write byte array to MySQL database from Java as image or file

javamysqlfilebytebytearray

提问by MinecraftShamrock

I want to save files to my MySQL database.

我想将文件保存到我的 MySQL 数据库中。

  1. Could I get the byte array from the file and store it in the database? Or is there any other way to save a file derectly in a MySQL database?

  2. What field type should I use to save a byte array to mysql and please give me an example query of how to insert an byte array

  1. 我可以从文件中获取字节数组并将其存储在数据库中吗?或者有没有其他方法可以将文件直接保存在 MySQL 数据库中?

  2. 我应该使用什么字段类型将字节数组保存到 mysql,请给我一个如何插入字节数组的示例查询

回答by f1sh

1) Yes. Read the file into a byte[]using FileInputStream.read(byte[]). Since an image consist of binary data, use a byte[](and not a String).

1) 是的。byte[]使用FileInputStream.read(byte[])将文件读入。由于图像由二进制数据组成,因此请使用 a byte[](而不是 String)。

2) The field in your database should be a blob, which is perfect for a byte[]. You can insert it using a PreparedStatement:

2) 数据库中的字段应该是 a blob,这对于byte[]. 您可以使用以下命令插入它PreparedStatement

PreparedStatement stmt = connection.generatePreparedStatement("INSERT INTO ... ");
stmt.setBytes(1, yourByteArray);

回答by npinti

I think you are looking for the Binary Large Object (BLOB). This should allow you to save a stream of bytes to your database. Thisexample should point you to the right direction when it comes to using BLOBs with MySQL and Java.

我认为您正在寻找二进制大对象 ( BLOB)。这应该允许您将字节流保存到数据库中。在将 BLOB 与 MySQL 和 Java 结合使用时,示例应该会为您指明正确的方向。

That being said, people usually do not recommend storing entire files to your database, what it is usually recommended is to store the file in your file system and just store the URI in your database. You can check thisprevious SO Post to see when you should use the BLOB.

话虽如此,人们通常不建议将整个文件存储到您的数据库中,通常建议将文件存储在您的文件系统中,并将 URI 存储在您的数据库中。您可以检查之前的SO帖子看的时候,你应该使用BLOB。

回答by Mark M

You can use varbinarydata type in MySQL for this. It matches to the type byte[]in Java.

varbinary为此,您可以在 MySQL 中使用数据类型。它与byte[]Java 中的类型匹配。