skip to Main Content

I am facing a java.lang.ClassNotFoundException error with the message com.mysql.cj.jdbc.Driver when attempting to run my Java code for data insertion into a MySQL database. Surprisingly, the code compiles and runs without any errors, but the data is not being inserted into the database. Here’s an overview of the issue:

  • I’m using Java and JDBC to connect to a MySQL database and insert data into a table.
  • I have made sure to include the MySQL JDBC driver JAR file in my project’s classpath.
  • When I run the code, I encounter the mentioned ClassNotFoundException error for the com.mysql.cj.jdbc.Driver class.
  • However, if I only compile the code without running it, there are no errors.
  • Despite the successful compilation, the data is not getting inserted into the database.

Here’s a snippet of the code where I connect the JDBC:

import java.sql.*;
public class Conn {
    /*
     * JDBC Connection has 4 Stages
     *  (1)-Register the Driver Class
     *  (2)-Creating Connection String
     *  (3)-Creating Statement
     *  (4)-Executing MySQL Queries
     *  (5)-Closing the Connection
     */

    Connection c; //reference variable
    Statement s; //
    Conn(){

        try{
            // (1)-Register the Driver Class
            Class.forName("com.mysql.cj.jdbc.Driver");
            //Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            System.out.println("Driver Loaded");
            // (2)-Creating Connection String
            /*
             * Connection String provides the information in which database you have connect
             */
            c= DriverManager.getConnection("jdbc:mysql://localhost:3306/universitymanagementsystem","root", "123456789");
            System.out.println("Connection Established");
            // (3)
            s= c.createStatement();

        }catch(Exception e){
            e.printStackTrace();
        }
    }
    /*public static java.beans.Statement createStatement() {
        return null;
    }*/
}

Here is the snippet of the code of AddStudent.java file

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.sql.*;
//import com.toedter.calendar.JDateChooser;

public class AddStudent extends JFrame implements ActionListener {
    JTextField tfname, tffname, tffaddress, tfphone, tfemail, tfX, tfXII, tfAdhar, tfdob;
    JLabel labelrollno;
    JComboBox<String> cbCourse, cbBranch;
    JButton btnSubmit, btnCancel;
    // JDateChooser dobChooser;
    /*
     * create a object for random class
     * which create some random number for roll number
     */

    Random ran = new Random();
    long first4 = Math.abs((ran.nextLong() % 9000L) + 1000L);

    AddStudent() {

        // for layout
        setSize(900, 700);
        setLocation(350, 50);
        setLayout(null); // cause we want our own layout

        // for heading
        JLabel heading = new JLabel("New student Details");
        heading.setBounds(310, 30, 500, 50);
        heading.setFont(new Font("serif", Font.BOLD, 30));
        add(heading);

        // name label
        JLabel labelName = new JLabel("Name");
        labelName.setBounds(50, 150, 100, 30);
        labelName.setFont(new Font("serif", Font.BOLD, 20));
        add(labelName);
        // name input box
        tfname = new JTextField();
        tfname.setBounds(200, 150, 150, 30);
        add(tfname);

        // father name label
        JLabel labelFName = new JLabel("Fathers Name");
        labelFName.setBounds(400, 150, 200, 30);
        labelFName.setFont(new Font("serif", Font.BOLD, 20));
        add(labelFName);
        // father name input box
        tffname = new JTextField();
        tffname.setBounds(600, 150, 150, 30);
        add(tffname);

        // roll name label
        JLabel lblRollNo = new JLabel("Roll Number");
        lblRollNo.setBounds(50, 200, 200, 30);
        lblRollNo.setFont(new Font("serif", Font.BOLD, 20));
        add(lblRollNo);
        setVisible(true);

        // roll nameinput box
        labelrollno = new JLabel("1533" + first4);
        labelrollno.setBounds(200, 200, 200, 30);
        labelrollno.setFont(new Font("serif", Font.BOLD, 20));
        add(labelrollno);
        setVisible(true);

        // date of birth
        JLabel lblDob = new JLabel("Date of Birth");
        lblDob.setBounds(400, 200, 200, 30);
        lblDob.setFont(new Font("serif", Font.BOLD, 20));
        add(lblDob);

        // date of birth input box
        tfdob = new JTextField();
        tfdob.setBounds(600, 200, 150, 30);
        add(tfdob);

        // date of birth input box
        /*
         * dobChooser = new JDateChooser();
         * dobChooser.setBounds(600, 200, 150, 30);
         * add(dobChooser);
         */

        // address label
        JLabel labeladdress = new JLabel("Address Name");
        labeladdress.setBounds(50, 250, 200, 30);
        labeladdress.setFont(new Font("serif", Font.BOLD, 20));
        add(labeladdress);
        // address name input box
        tffaddress = new JTextField();
        tffaddress.setBounds(200, 250, 150, 30);
        add(tffaddress);

        // phone number label
        JLabel labelPhone = new JLabel("Phone Number");
        labelPhone.setBounds(400, 250, 200, 30);
        labelPhone.setFont(new Font("serif", Font.BOLD, 20));
        add(labelPhone);
        // phone number input box
        tfphone = new JTextField();
        tfphone.setBounds(600, 250, 150, 30);
        add(tfphone);

        // Email Id
        JLabel labelemail = new JLabel("Email Id");
        labelemail.setBounds(50, 300, 200, 30);
        labelemail.setFont(new Font("serif", Font.BOLD, 20));
        add(labelemail);
        // Email Id input box
        tfemail = new JTextField();
        tfemail.setBounds(200, 300, 150, 30);
        add(tfemail);

        // Class X label
        JLabel labelX = new JLabel("Class X(%)");
        labelX.setBounds(400, 300, 200, 30);
        labelX.setFont(new Font("serif", Font.BOLD, 20));
        add(labelX);
        // Class X input box
        tfX = new JTextField();
        tfX.setBounds(600, 300, 150, 30);
        add(tfX);

        // Class XII label
        JLabel labelXII = new JLabel("Class XII(%)");
        labelXII.setBounds(50, 350, 200, 30);
        labelXII.setFont(new Font("serif", Font.BOLD, 20));
        add(labelXII);
        // Class XII input box
        tfXII = new JTextField();
        tfXII.setBounds(200, 350, 150, 30);
        add(tfXII);

        // Adhar Number label
        JLabel labelAdhar = new JLabel("Adhar Number");
        labelAdhar.setBounds(400, 350, 200, 30);
        labelAdhar.setFont(new Font("serif", Font.BOLD, 20));
        add(labelAdhar);
        // Adhar Number input box
        tfAdhar = new JTextField();
        tfAdhar.setBounds(600, 350, 150, 30);
        add(tfAdhar);

        // dropdown for course
        /*
         * JLabel labelCourse = new JLabel("Course");
         * labelCourse.setBounds(50, 400, 200, 30);
         * labelCourse.setFont(new Font("serif", Font.BOLD, 20));
         * add(labelCourse);
         * String course[] = { "B.Tech", "M.Tech", "BBA", "MBA", "BCA", "MCA" };
         * cbCourse = new JComboBox(course);
         * cbCourse.setBounds(200, 400, 150, 30);
         * cbCourse.setBackground(Color.WHITE);
         * add(cbCourse);
         */

        // dropdown for course
        JLabel labelCourse = new JLabel("Course");
        labelCourse.setBounds(50, 400, 200, 30);
        labelCourse.setFont(new Font("serif", Font.BOLD, 20));
        add(labelCourse);

        String course[] = { "B.Tech", "M.Tech", "BBA", "MBA", "BCA", "MCA" };
        cbCourse = new JComboBox<>(course);
        cbCourse.setBounds(200, 400, 150, 30);
        cbCourse.setBackground(Color.WHITE);
        add(cbCourse);

        // dropdown for branch
        JLabel labelBranch = new JLabel("Branch");
        labelBranch.setBounds(400, 400, 200, 30);
        labelBranch.setFont(new Font("serif", Font.BOLD, 20));
        add(labelBranch);

        String[] branch = { "CSE", "ECE", "EEE", "ME", "CE", "IT", "Not Applicable" };
        cbBranch = new JComboBox<>(branch);
        cbBranch.setBounds(600, 400, 150, 30);
        cbBranch.setBackground(Color.WHITE);
        add(cbBranch);

        // submit button
        btnSubmit = new JButton("Submit");
        btnSubmit.setBounds(200, 450, 150, 30);
        btnSubmit.setBackground(Color.BLACK);
        btnSubmit.setForeground(Color.WHITE);
        btnSubmit.addActionListener(this);
        add(btnSubmit);

        // cancel button
        btnCancel = new JButton("Cancel");
        btnCancel.setBounds(400, 450, 150, 30);
        btnCancel.setBackground(Color.BLACK);
        btnCancel.setForeground(Color.WHITE);
        btnCancel.addActionListener(this);
        add(btnCancel);

        setVisible(true);

    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == btnSubmit) {
            // taking all the values
            String fname = tfname.getText();
            String ffname = tffname.getText();
            String rollno = labelrollno.getText();
            String dob = tfdob.getText();
            String address = tffaddress.getText();
            String phone = tfphone.getText();
            String email = tfemail.getText();
            String class_x = tfX.getText();
            String class_xii = tfXII.getText();
            String adhar = tfAdhar.getText();
            String course = (String) cbCourse.getSelectedItem();
            String branch = (String) cbBranch.getSelectedItem();

            // inserting into database

            try {
                String query = "insert into student values('"+fname+"', '"+ffname+"', '"+rollno+"', '"+dob+"', '"+address+"', '"+phone+"', '"+email+"', '"+class_x+"', '"+class_xii+"', '"+adhar+"', '"+course+"', '"+branch+"')";

                Conn con = new Conn();
                con.s.executeUpdate(query);
                
                JOptionPane.showMessageDialog(null, "Student Details Inserted Successfully");
                setVisible(false);
            } catch (Exception e) {
                e.printStackTrace();
            }

    
        } else {
            setVisible(false);

        }
    }

    public static void main(String[] args) {
        new AddStudent();
    }
}

Here is the proof that I already include the mysql-Connector jar file
enter image description here

Error and excception while I run the code

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)     
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)  
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:375)
        at Conn.<init>(Conn.java:19)
        at AddStudent.actionPerformed(AddStudent.java:225)
        at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)       
        at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)   
        at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
        at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
        at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
        at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
        at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
        at java.desktop/java.awt.Component.processEvent(Component.java:6391)
        at java.desktop/java.awt.Container.processEvent(Container.java:2266)
        at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
        at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
        at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
        at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
        at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
        at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
        at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
        at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
        at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
        at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
        at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
        at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
        at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
java.lang.NullPointerException: Cannot invoke "java.sql.Statement.executeUpdate(String)" because "<local15>.s" is null
        at AddStudent.actionPerformed(AddStudent.java:226)
        at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
        at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
        at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
        at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
        at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
        at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
        at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
        at java.desktop/java.awt.Component.processEvent(Component.java:6391)
        at java.desktop/java.awt.Container.processEvent(Container.java:2266)
        at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
        at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
        at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
        at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
        at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
        at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
        at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
        at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
        at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
        at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
        at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
        at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
        at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

But when I hit Run Java that time no problem but the data is not inserted into database

enter image description here

Data is not insert image

enter image description here

I have been working on a Java code snippet to insert data into a MySQL database table, but I’m encountering unexpected behavior. Here’s a summary of what I’ve tried and the expected outcome:

I have established a JDBC connection to the MySQL database using the appropriate connection parameters (URL, username, and password).
After successfully establishing the connection, I attempted to insert data into the table using an SQL insert statement.
However, despite running the code without any errors, the data is not being stored in the database table as expected.

I was expecting the code to insert the provided data into the specified table, but it seems to complete without any errors, yet the data is not being stored. I have verified that the connection parameters and SQL query are correct.

Any guidance or suggestions regarding this issue would be greatly appreciated. Thank you in advance for your help!

2

Answers


  1. There could be multiple reasons for ClassNotFoundException :

    [1] Incorrect Jar Placement: Ensure that you have placed the MySQL jar file in the correct location within your project structure. Typically, you would add the jar file to the "lib" folder or include it as a dependency in your build tool configuration (e.g., Maven or Gradle).

    [2] Jar file compatibility : Make sure your jar file compatible with your MySQL server version. For example if you are using MySQL latest version then you should use latest/newer version of MySQL connector jar file

    [3] IDE Configuration : If you are using IntelliJ or Eclipse then correctly setting into your project settings or build path

    Login or Signup to reply.
  2. make sure you have add the mysql Driver jar. Since you use reflection to load class Driver, it won’t prompt errors when compiling.Only when the code is running to the process of loading class Driver, errors merge.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search