简体   繁体   中英

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

I want to save files to my MySQL database.

  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) 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).

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

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

I think you are looking for the Binary Large Object ( BLOB ). This should allow you to save a stream of bytes to your database. This example should point you to the right direction when it comes to using BLOBs with MySQL and 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 this previous SO Post to see when you should use the BLOB.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM