Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to insert and retrieve image from MySQL (DB) to Java?

user-image
Question added by Usama Saad , Senior Software Engineer (Java) , Saudi Catering Company
Date Posted: 2013/08/18
Usama Saad
by Usama Saad , Senior Software Engineer (Java) , Saudi Catering Company

I will answer this question using demo consist of3 steps :   1.
Creating the Image column: the image column will save a file , so it's recommend to make its  type blob.Ex :   CREATE  TABLE `mydb`.`tablename` (  `id` INT NOT NULL AUTO_INCREMENT ,  `image` BLOB NULL ,  `image_name` VARCHAR(45) NULL ,  PRIMARY KEY (`id`) ); 2.
Java code to insert Image :             File image = new File("c:/Me.jpg");             psmnt = connection.prepareStatement("insert into tablename (image , image_name) " + "values(? ,?)");             fis = new FileInputStream(image);             psmnt.setBinaryStream(1, (InputStream) fis, (int) (image.length()));             psmnt.setString(2,image.getName());            psmnt.executeUpdate(); 3.
Retrieve file from db :        rs = stmt.executeQuery("SELECT image , image_name FROM tablename ");        String filename = "";             while (rs.next()) {                 filename = rs.getString(2);                 Blob test = rs.getBlob("image");                 InputStream x = test.getBinaryStream();                 int size = x.available();                 OutputStream out = new FileOutputStream("c:/"+filename);                 byte b[] = new byte[size];                 x.read(b);                 out.write(b);             } .To handle retrieving Image in easy way .
you can do below code in steps after line 5             byte[] image = rs.getBytes("image")             Image img = Toolkit.getDefaultToolkit().createImage(image);             ImageIcon icon = new ImageIcon(img); refrence http://usama-saad.blogspot.com/2013/07/how-to-insert-and-retrieve-image-from.html

Salman Mansoor
by Salman Mansoor , Digital Strategist / Social Media Strategist , RockSol | Digital Creative Agency | Software House

You can use blob datatype for your image.Here is the sample link for your requirements.And the other way is changing image into byte data and store it into your database with byte datatype.But I personally not recommended storing image into database

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.