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

arrays, byte, file, java, mysql

Solution

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

Problem

I want to save files to my MySQL database. 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? 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

Original source

Related problems