Java MySQL - Images - INSERT, SELECT then show in JLIst

October 28, 2017 Oclemy Java MySQL, Java JList 8 minutes, 4 seconds

Java MySQL : Images - INSERT, SELECT then show in JLIst

This is an example that explores how to save/insert images into MySQL database. We also retrieve that image and display it in a JList.

Screenshot

  • Here's the screenshot of the project.

Java Swing Save/Retrieve Image into MySQL database

Java MySQL Images JList

Save Images in MySQL database as Blob

Java MySQL Image blob

Common Questions this example explores

  • How to save image into MySQL database in java.
  • How to retrieve images from MySQL database java.
  • Fetch image from MySQL to JList.
  • Retrieving images from mysql database
  • Insert, select image mysql database java jlist.
  • Java MySQL Image example.
  • How to show images and text in java jlist.

Tools Used

This example was written with the following tools:

  • Windows 8
  • Netbeans IDE

Source Code

Lets jump directly to the source code. \

DBClass.java

  • Our database class.
package imagedb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JList;

public class DBClass {

      String conString="jdbc:mysql://localhost:3306/imagesdb";
      String username="root";
      String pswd="";
      PreparedStatement ps;

      JList list=new JList();
      DefaultListModel dm=new DefaultListModel();

      public DBClass(JList jlist)
      {
          this.list=jlist;
      }

      //INSERT IMG INTO DB
      public Boolean add(File img,FileInputStream fis)
      {
          try {
              //SQL STMT
              String sql="INSERT INTO imagestb(Image) VALUES(?)";
              //CONNECTION
              Connection con=DriverManager.getConnection(conString, username, pswd);

              //STATEMENT
              ps=con.prepareStatement(sql);

              ps.setBinaryStream(1, fis);

              //EXECUTE
              ps.executeUpdate();

              return true;

          } catch (SQLException ex) {
              Logger.getLogger(DBClass.class.getName()).log(Level.SEVERE, null, ex);
              return false;
          }

      }
       //RETRIEVE IMG
      public Boolean retrieve()
      {
          try {
              FileOutputStream fos=null;

              //SQL STMT
              String sql="SELECT * FROM imagestb";

              //CONNECTION
              Connection con=DriverManager.getConnection(conString, username, pswd);
              //STATEMENT
              ps=con.prepareStatement(sql);

              //OUR RESULTSET
               ResultSet rs=ps.executeQuery();

               String id="";
               Blob b=null;

               //LOOP
               while(rs.next())
               {
                   //GET CELL VALUES PER ROW
                   id=rs.getString("ID");
                   b=rs.getBlob("Image");

                    //PATH
                   String path="D://Imgs/"+id+".jpg";

                   //WRITE FILE TO OUR MACHINE
                   fos=new FileOutputStream(path);

                   int len=(int) b.length();
                   byte[] imgData=b.getBytes(1, len);

                   fos.write(imgData,0,len);

                   this.addImages(path);
               }

               return true;

          } catch (SQLException ex) {
              Logger.getLogger(DBClass.class.getName()).log(Level.SEVERE, null, ex);
          } catch (FileNotFoundException ex) {
              Logger.getLogger(DBClass.class.getName()).log(Level.SEVERE, null, ex);
          } catch (IOException ex) {
              Logger.getLogger(DBClass.class.getName()).log(Level.SEVERE, null, ex);
          }

          return false;

      }

      //ADD TO JLIST
      private void addImages(String path)
      {
          ImageIcon icon=new ImageIcon(path);
          dm.addElement(icon);

          list.setModel(dm);
      }

}

 

GUIClass.java

  • Our GUI class.
package imagedb;

import java.awt.FileDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

import javax.swing.ImageIcon;

import javax.swing.JOptionPane;

public class GUIClass extends javax.swing.JFrame {
String path="";

    public GUIClass() {
        initComponents();
    }

    //SAVE
    private void save()
    {
    try {
        FileInputStream fis=null;
        File img =null;

        img=new File(path);
        fis=new FileInputStream(img);

        if(new DBClass(jList1).add(img,fis))
        {
            JOptionPane.showMessageDialog(null, "Sucessfully Saved");
            fileLabel.setIcon(null);
        }else
        {
            JOptionPane.showMessageDialog(null, "Not Saved");
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(GUIClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        saveBtn = new javax.swing.JButton();
        retrieveBtn = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        clearBtn = new javax.swing.JButton();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        fileLabel = new javax.swing.JLabel();
        jInternalFrame2 = new javax.swing.JInternalFrame();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        saveBtn.setText("Save");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        retrieveBtn.setText("Retrieve");
        retrieveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                retrieveBtnActionPerformed(evt);
            }
        });

        jLabel3.setText("ProgrammingWizards Channel");

        jLabel5.setText("Load and save From File");

        clearBtn.setText("Clear");
        clearBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearBtnActionPerformed(evt);
            }
        });

        jInternalFrame1.setVisible(true);

        fileLabel.setBackground(new java.awt.Color(204, 204, 204));
        fileLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        fileLabel.setText("Browse");
        fileLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fileLabelMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(fileLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(fileLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jInternalFrame2.setVisible(true);

        jPanel1.setBackground(new java.awt.Color(45, 155, 193));

        jLabel4.setText("FROM THE DATABASE");

        jScrollPane2.setViewportView(jList1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addGap(126, 126, 126))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jInternalFrame2Layout = new javax.swing.GroupLayout(jInternalFrame2.getContentPane());
        jInternalFrame2.getContentPane().setLayout(jInternalFrame2Layout);
        jInternalFrame2Layout.setHorizontalGroup(
            jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jInternalFrame2Layout.setVerticalGroup(
            jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(232, 232, 232))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jInternalFrame2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(112, 112, 112)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(jLabel5))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(saveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(retrieveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(158, 158, 158)
                        .addComponent(clearBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(87, 87, 87))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(36, 36, 36)
                        .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(69, 69, 69)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(saveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(retrieveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31)
                        .addComponent(clearBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jInternalFrame2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
     this.save();
    }//GEN-LAST:event_saveBtnActionPerformed

    private void fileLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileLabelMouseClicked
       FileDialog fd=new FileDialog(this);
       fd.show();
       path=fd.getDirectory()+fd.getFile();

       fileLabel.setIcon(new ImageIcon(path));
    }//GEN-LAST:event_fileLabelMouseClicked

    private void retrieveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_retrieveBtnActionPerformed
      if(new DBClass(jList1).retrieve())
      {
      JOptionPane.showMessageDialog(null, "Sucessfully Retrieved");

        }else
        {
            JOptionPane.showMessageDialog(null, "Not retrieved");
        }
    }//GEN-LAST:event_retrieveBtnActionPerformed

    private void clearBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearBtnActionPerformed
       fileLabel.setIcon(null);
       jList1.setModel(new DefaultListModel());
    }//GEN-LAST:event_clearBtnActionPerformed

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUIClass().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearBtn;
    private javax.swing.JLabel fileLabel;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JInternalFrame jInternalFrame2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton retrieveBtn;
    private javax.swing.JButton saveBtn;
    // End of variables declaration//GEN-END:variables
}

 

ImagesDB.java

  • Our main class.
package imagedb;

import javax.swing.UIManager;

public class ImageDB {

    public static void main(String[] args) {

//                 try {
//                    // select Look and Feel
//                    UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
//            // start application
//
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
                 new GUIClass().setVisible(true);
    }

}

 

Video/Preview

https://www.youtube.com/watch?v=HpEXGYWXIWQ

How To Run

  1. Copy the source code above.
  2. Paste it into your project and edit it.

More

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.

Comments