JDBC How To Upload Blob Image Into Mysql Database Using Java, Xampp And Netbeans IDE

JDBC How To Upload Blob Image Into Mysql Database Using Java, Xampp And Netbeans IDE

JDBC How To Upload Blob Image Into Mysql Database Using Java, Xampp And Netbeans IDE

What’s Covered In this guide :

  1. Selecting Image from the computer using JFileChooser.
  2. Displaying image on a jlabel.
  3. Choosing Only Images By Filtering the image extensions using FileNameExtensionFilter.
  4. Changing Default Try Catch error handling from Logger to printstacktrace.
  5. Connecting to xampp localhost.
  6. Connecting to database.
  7. Changing server timezone.
  8. Creating new database.
  9. Creating new mysql table.
  10. Inserting Image Into Mysql Database as a BLOB (BINARY LARGE OBJECT).
/*
 * JDBC How To Upload Blob Image Into Mysql Database Using Java, Xampp And Netbeans IDE
 */
package javanetbeansinsertblobimageintomysqldatabase;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Genuine
 */
public class JAVANetbeansInsertBLOBImageIntoMysqlDatabase extends javax.swing.JFrame {

    /**
     * Creates new form JAVANetbeansInsertBLOBImageIntoMysqlDatabase
     */
    public JAVANetbeansInsertBLOBImageIntoMysqlDatabase() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        labelDisplayImage = new javax.swing.JLabel();
        btnChooseImageFromComputer = new javax.swing.JButton();
        btnDisplayBlobImage = new javax.swing.JButton();
        textFieldDisplayPath = new javax.swing.JTextField();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(800, 600));

        btnChooseImageFromComputer.setText("Load Image ///");
        btnChooseImageFromComputer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseImageFromComputerActionPerformed(evt);
            }
        });

        btnDisplayBlobImage.setText("Upload Image");
        btnDisplayBlobImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDisplayBlobImageActionPerformed(evt);
            }
        });

        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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnChooseImageFromComputer, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                    .addComponent(btnDisplayBlobImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textFieldDisplayPath))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(labelDisplayImage, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(labelDisplayImage, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(textFieldDisplayPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 167, Short.MAX_VALUE)
                .addComponent(btnChooseImageFromComputer, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDisplayBlobImage, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    String timeZone = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String user = "root";
    String password = "";
    String jdbcDriver = "com.mysql.cj.jdbc.Driver";
    String databaseName = "JAVANetbeansInsertBLOBImageIntoMysqlDatabase";
    String checkIfDatabaseExixtsSQL = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + databaseName + "'";
    String createNewDatabaseSQL = "CREATE DATABASE IF NOT EXISTS " + databaseName;
    String createNewTableSQL = "CREATE TABLE IF NOT EXISTS `insertimageintomysqldatabaseasblog` (\n"
            + "  `Id` int(11) NOT NULL AUTO_INCREMENT,\n"
            + "  `ImageName` varchar(200) NOT NULL,\n"
            + "  `ImagePath` varchar(200) NOT NULL,\n"
            + "  `ImageFile` longblob NOT NULL,\n"
            + "  PRIMARY KEY (`Id`)\n"
            + ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";
    String insertImageImageIntoMysqlDatabaseSQL = "INSERT INTO `insertimageintomysqldatabaseasblog`(`ImageName`, `ImagePath`, `ImageFile`) VALUES (?,?,?)";
    Statement stmt = null;
    ResultSet rs = null;
    PreparedStatement pst = null;
    boolean databaseExists = false;
    String selectedImagePath = null;
    String filename = null;
    InputStream inputstream = null;

    private void btnChooseImageFromComputerActionPerformed(java.awt.event.ActionEvent evt) {                                                           
        // TODO add your handling code here:
        JFileChooser filechooser = new JFileChooser();
        //choose only "png", "jpg", "jpeg"
        FileNameExtensionFilter fnef = new FileNameExtensionFilter("IMAGES", "png", "jpg", "jpeg");
        filechooser.addChoosableFileFilter(fnef);
        int openDialog = filechooser.showOpenDialog(null);
        if (openDialog == filechooser.APPROVE_OPTION) {
            File selectedFile = filechooser.getSelectedFile();
            selectedImagePath = selectedFile.getAbsolutePath();
            filename = selectedFile.getName();
            textFieldDisplayPath.setText(selectedImagePath);
            ImageIcon ii = new ImageIcon(selectedImagePath);
            //resizing image to fit jlabel
            Image image = ii.getImage().getScaledInstance(labelDisplayImage.getWidth(), labelDisplayImage.getHeight(), Image.SCALE_SMOOTH);

            labelDisplayImage.setIcon(new ImageIcon(image));
        }

    }                                                          

    private void btnDisplayBlobImageActionPerformed(java.awt.event.ActionEvent evt) {                                                    

        try {
            // TODO add your handling code here:

            //Check jdbc Driver
            Class.forName(jdbcDriver);
            System.out.println("Driver Found !!...............");
            //Connecting to server (Xampp Localhost)
            conn = DriverManager.getConnection(url + timeZone, user, password);
            System.out.println("Connected To Server Successfully..............");
            System.out.println("Database Query = " + checkIfDatabaseExixtsSQL);
            stmt = conn.createStatement();
            rs = stmt.executeQuery(checkIfDatabaseExixtsSQL);
            if (rs.next()) {
                System.out.println("Database Found");
                databaseExists = true;
                //Connecting To Existing Database
                conn = DriverManager.getConnection(url + databaseName + timeZone, user, password);
                //Connected To Existing Database
                System.out.println("Connected To Existing Database -  " + databaseName);
                //Inserting Data Into The Database
                System.out.println("Inserting Data Into The Database.. ");
                InsertDataIntoMysqlDatabase();
            }

            if (!databaseExists) {
                System.out.println("Database Not Found");
                System.out.println("Creating new Database");
                System.out.println("Create Database Query = " + createNewDatabaseSQL);
                int databaseCreated = stmt.executeUpdate(createNewDatabaseSQL);
                if (databaseCreated > 0) {
                    System.out.println(databaseName + " Database Created");
                    //Connecting to newly create database
                    conn = DriverManager.getConnection(url + databaseName + timeZone, user, password);
                    System.out.println("Connected To Newly Created Database - " + databaseName);
                    System.out.println("Creating New Mysql Table ........");
                    System.out.println("Table Query - " + createNewTableSQL);
                    stmt = conn.createStatement();
                    stmt.executeUpdate(createNewTableSQL);
                    System.out.println("New Table Created .......... ");

                    //Inserting Data Into The Database
                    System.out.println("Inserting Data Into The Database.. ");

                    InsertDataIntoMysqlDatabase();
                }
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            System.out.println("Driver Not Found !!..............");
            ex.getMessage();
        }


    }                                                   
    private void InsertDataIntoMysqlDatabase() {
        System.out.println("Image Name - " + filename);
        System.out.println("Image Absolute Path - " + selectedImagePath);

        try {
            inputstream = new FileInputStream(new File(selectedImagePath));

            pst = conn.prepareStatement(insertImageImageIntoMysqlDatabaseSQL);
            pst.setString(1, filename);
            pst.setString(2, selectedImagePath);
            pst.setBlob(3, inputstream);
            int updateData = pst.executeUpdate();
            if (updateData > 0) {
                JOptionPane.showMessageDialog(null, "Image Uploaded");

                System.out.println("Image Inserted.......... ");
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JAVANetbeansInsertBLOBImageIntoMysqlDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JAVANetbeansInsertBLOBImageIntoMysqlDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JAVANetbeansInsertBLOBImageIntoMysqlDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JAVANetbeansInsertBLOBImageIntoMysqlDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JAVANetbeansInsertBLOBImageIntoMysqlDatabase().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnChooseImageFromComputer;
    private javax.swing.JButton btnDisplayBlobImage;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel labelDisplayImage;
    private javax.swing.JTextField textFieldDisplayPath;
    // End of variables declaration                   

}

When you run the script the first time it checks if the database exists. If it doesn’t, then new database is created and new table is also created, Finally, blob image is inserted into currently created mysql table.

run:
Driver Found !!...............
Connected To Server Successfully..............
Database Query = SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'JAVANetbeansInsertBLOBImageIntoMysqlDatabase'
Database Not Found
Creating new Database
Create Database Query = CREATE DATABASE IF NOT EXISTS JAVANetbeansInsertBLOBImageIntoMysqlDatabase
JAVANetbeansInsertBLOBImageIntoMysqlDatabase Database Created
Connected To Newly Created Database - JAVANetbeansInsertBLOBImageIntoMysqlDatabase
Creating New Mysql Table ........
Table Query - CREATE TABLE IF NOT EXISTS `insertimageintomysqldatabaseasblog` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `ImageName` varchar(200) NOT NULL,
  `ImagePath` varchar(200) NOT NULL,
  `ImageFile` longblob NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
New Table Created .......... 
Inserting Data Into The Database.. 
Image Name - Penguins.jpg
Image Absolute Path - C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg
Image Inserted.......... 
BUILD SUCCESSFUL (total time: 46 seconds)

When you run the app second time it selects already existing database base and doesn’t create new table, instead, it uploads image into the previously created table.

run:
Driver Found !!...............
Connected To Server Successfully..............
Database Query = SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'JAVANetbeansInsertBLOBImageIntoMysqlDatabase'
Database Found
Connected To Existing Database -  JAVANetbeansInsertBLOBImageIntoMysqlDatabase
Inserting Data Into The Database.. 
Image Name - Jellyfish.jpg
Image Absolute Path - C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg
Image Inserted.......... 
BUILD SUCCESSFUL (total time: 25 seconds)

 JDBC How To Upload Blob Image Into Mysql Database Using Java - Main App
JDBC How To Upload Blob Image Into Mysql Database Using Java – Main App
 JDBC How To Upload Blob Image Into Mysql Database Using Java - Selecting Image From The Computer
JDBC How To Upload Blob Image Into Mysql Database Using Java – Selecting Image From The Computer
 JDBC How To Upload Blob Image Into Mysql Database Using Java - Displaying Image On A Jlabel
JDBC How To Upload Blob Image Into Mysql Database Using Java – Displaying Image On A Jlabel
 JDBC How To Upload Blob Image Into Mysql Database Using Java - PhpMyAdmin Images Inserted As Blob
JDBC How To Upload Blob Image Into Mysql Database Using Java – PhpMyAdmin Images Inserted As Blob

Leave a Reply

Your email address will not be published. Required fields are marked *