Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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

share|improve this question
    
You can directly save the file to database using BLOB/CLOB type of columns – Reddy Jul 16 '13 at 9:32
    

3 Answers 3

up vote 5 down vote accepted

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);
share|improve this answer

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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.