skip to Main Content

I created a utility class to handle database connections using JDBC. I get the error below in another class, performing actions such as displaying the values from the database:

"Cannot invoke "java.sql.Connection.prepareStatement(String)" because "Utils.connection" is null"

I have another class where the connection works like a charm.

//// This is the connection class.

import java.sql.*;

public class Utils { 

    public static Connection connection ; 
    public static PreparedStatement preStmt;
    public static ResultSet rs;

    public static  void Connect() {
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "");      
            System.out.println("DataBase Connected ;)");

        } catch (SQLException e) { 
            throw new RuntimeException(e); 
        } 
    }
} 

/////// This is the other class where I get the error message

import javax.swing.*;
import java.sql.SQLException;

public class Contacts {

    static JFrame frame = new JFrame("Contacts");
    private JButton searchButton;
    private JTextField textSearch;
    private JList list;
    private JButton createButton;
    private JButton deleteButton;
    private JButton editButton;
    private JPanel Main;
    private DefaultListModel<String> listModel;

    public static void main(String[] args) {
        frame.setContentPane(new Contacts().Main);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setSize(500, 700);

        Utils.Connect();
    }

    public Contacts() {
        DefaultListModel<String> listModel = new DefaultListModel<>();
        list.setModel(listModel);

        loadContacts(); 
    }

    public void loadContacts() { 
        String name;
        String number;
        String address;

        listModel.clear();

        try {
            Utils.preStmt = Utils.connection
                .prepareStatement("SELECT * FROM contactsdb WHERE id =?");     
            Utils.preStmt.setString(1, String.valueOf(list)); 
            Utils.rs = Utils.preStmt.executeQuery();

            while (Utils.rs.next()) {
                name = Utils.rs.getString(1);
                number = Utils.rs.getString(2);
                address = Utils.rs.getString(3);
                listModel.addElement(name + " " + number + " " + address);
                listModel.addElement(number); listModel.addElement(address); 
            } 
        } catch (SQLException e) {
            e.printStackTrace(); 
        } 
    }   
} 

2

Answers


  1. You are creating the connection after loadContacts() method is invoked. Therefore, you get the infamous NullPointerException.

    Calling Utils.Connect() before loadContacts() should fix the issued.

    I advise you to look for good practices for managing database connections with JDBC. For instance, the Connection, PreparedStatement and ResultSet instances should be closed after each use, even when there is a failure.

    Login or Signup to reply.
  2. You are calling loadContacts() before creating your connection.

    This line is calling the constructor for Contacts, which calls loadContacts():

    frame.setContentPane(new Contacts().Main);
    

    To fix your code, just change the order of your main method so your connection is initialized before you call loadContacts():

    public static void main(String[] args) {
        Utils.Connect();
    
        frame.setContentPane(new Contacts().Main);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setSize(500, 700);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search