Home > Java > How To Store Data In Blob Column Type Using Java

How To Store Data In Blob Column Type Using Java

May 22nd, 2008

Some code to help update/upload an image file’s bytes into a MySQL database.

Listed below is the source code of a simple DAO class, whose setIconImageFileBytes method is responsible to update/upload an image’s bytes into the database.


01 import java.io.ByteArrayInputStream;
02 import java.sql.Connection;
03 import java.sql.PreparedStatement;
04 import java.sql.ResultSet;
05 import java.sql.SQLException;
06 import java.sql.Statement;
07 
08 public class SomeDAO
09 {
10   private void printWarn(String mssg)
11   { System.out.println(mssg);
12     //logger.warn(prfx + mssg);
13   }// end-of-printWarn
14   
15   /**
16    * Sets the image's bytes.
17    @param userID
18    @param avatarImageFileBytes
19    @param con java.sql.Connection object to use
20    @return boolean to indicate success or failure of this operation
21    */
22   public boolean setIconImageFileBytes(
23       int userID,
24       byte[] avatarImageFileBytes,
25       Connection con)
26   {
27     boolean isSet = false;
28     if(con != null)
29     { // Executing the UPDATE
30       try
31       {
32         String sqlStr = "UPDATE users SET avatar_image_file=? WHERE user_id=?";
33         PreparedStatement pStmt = con.prepareStatement(sqlStr);
34         pStmt.setBinaryStream(1new ByteArrayInputStream(avatarImageFileBytes),
35             (intavatarImageFileBytes.length);
36         pStmt.setInt(2, userID);
37         pStmt.executeUpdate();
38         pStmt.close();
39         // Closing a ByteArrayInputStream has no effect, therefore is not done
40         pStmt = null;
41         isSet = true;
42       }
43       catch(SQLException e)
44       {
45         printWarn("SQLException caught when updating the 'avatar_image_file' "
46             + "field for user, ID " + userID + ". Exception message : "
47             + e.getMessage());
48         //e.printStackTrace(); //uncomment if you wish to see the stack trace
49       }
50     }
51     else
52       printWarn("Connection from pool is NULL inside 'setIconImageFileBytes'");
53 
54     return isSet;
55   }// end-of-setIconImageFileBytes
56 }

The avatar_image_file column is of the BLOB column type. Code has been tested using a MySQL database. I have ommitted the code to get/create a JDBC connection.

Categories: Java Tags:
Comments are closed.