hi everyone. can any of you guide me asto how to avoid null pointer exception in the result set variable.i am using this function to get all data in mysql table in hashtable. how to i take the scenario if there was no data in the table at time of execution. ie. the first time the programe was executed with nothing in database. since the table has nothing and resultSet is is pointed to null gives null pointer exception. how can i deal with that. thanks in advance
kesh.

static void readDatabase() throws Exception{
		    try{
		    	
				// This will load the MySQL driver, each DB has its own driver
				Class.forName("com.mysql.jdbc.Driver");
				// Setup the connection with the DB
				connect = DriverManager
						.getConnection("jdbc:mysql://localhost/mydatabase?"
								+ "user=sqldata&password=sqldatapw");

				resultSet = statement
				.executeQuery("select * from MYDATABASE.CUSTOMER");
				
		      CusList = (CustomerList)resultSet;
				
		      System.out.println("files reloaded.");
		    }
		 catch (Exception e) {
			throw e;
		} finally {
			close();
		}
		    
	
		  }

Dani AI

Generated

A few clarifications that help diagnose and fix the NullPointerException in this thread.

The JDBC call executeQuery(...) will normally return a non-null ResultSet even when the query finds zero rows; an NPE is therefore usually caused by something else (an uninitialised Connection or Statement, calling methods on the ResultSet before positioning it, or shared static DB objects that were never created). This aligns with 's advice to avoid exposing/using shared static DB objects and with 's suggestion to check for nulls and design the DB access method properly.

A safe, simple pattern (Java 7+) is to open and close resources in the same method and to check rs.next() to detect "no rows". Example that returns an empty map instead of null:

private static Map<Integer,Customer> loadCustomers(String url, String user, String pass) throws SQLException {
    String sql = "SELECT id, name, email FROM CUSTOMER";
    Map<Integer,Customer> result = new HashMap<>();
    try (Connection conn = DriverManager.getConnection(url, user, pass);
         PreparedStatement ps = conn.prepareStatement(sql);
         ResultSet rs = ps.executeQuery()) {

        if (!rs.next()) {
            return result; // empty table -> return empty map
        }

        do {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String email = rs.getString("email");
            result.put(id, new Customer(id, name, email));
        } while (rs.next());
    }
    return result;
}

Troubleshooting notes:

  • Inspect the stack trace to find which variable is null (if the NPE points at the executeQuery line, statement was likely null).
  • Do not cast a ResultSet to a collection; iterate and build the collection row-by-row.
  • Prefer returning an empty collection (HashMap/ArrayList) instead of null — callers are simpler and safer.
  • If stuck on an older Java version, mimic try-with-resources by closing ResultSet, Statement and Connection in a finally block in reverse order.

These steps both prevent the NPE and produce a cleaner, more maintainable way to read table data into a collection.

Recommended Answers

All 9 Replies

So much wrong with that method I don't even know where to begin...

1) don't make it static.
2) don't reference outside variables, certainly never do so without checking them for validity first.
3) use proper means to open a connection, don't put username and password into the url like that, certainly not unencrypted.
4) don't just rethrow exceptions like that
5) properly close all database entities, and in the same method you open them.
6) don't expose database entities to the outside world
7) don't think you can cast a resultset to something else

6) is what causes your NPE, but it's a symptom of a major design flaw rather than the actual problem.

if i dont put it to static i wont be able to use it in my edit dialogbox. its a big project and im a newby . making it work was the first task for me.i could correct the exceptions and other things later.right now the only probelm i am faced with is the resultset being null.it works perfect if and only if there is atleast one row in the table already.

jwenting is right, and you are wrong about not being able to use it in your dialogbox. But anyway, you can check if something is null like this:

if (resultset == null) {
   System.out.println("No records found");
} else {
   // do whatever it is you wanted to do with the resultset
}

(but please don't ignore jwenting's advice)

see when i first create or execute the class i need to use these function. here this is what i mean.

public class CusRec extends ViewElements
{

	private static Connection connect = null;
	private static Statement statement = null;
	private static PreparedStatement preparedStatement = null;
	private static ResultSet resultSet = null;
	
  //main
  public static void main(String[] args) throws Exception{
    System.out.println("Loading...");

    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception e) {}
    String title = "Customer ";
    JFrame main = new CusRec(title);
    
    Toolkit thKit = main.getToolkit();
    Dimension wndSze = thKit.getScreenSize();
    main.pack();
    int wd = main.getWidth();
    int ht = main.getHeight();
    int x = (int)((wndSze.getWidth()/2)-(wd/2));
    int y = (int)((wndSze.getHeight()/2)-(ht/2));
    main.setBounds(x,y,wd,ht);
    main.setVisible(true);
    main.setResizable(false);
    main.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  }
  CusRec(String title) throws Exception{
    super(title);
    System.out.println("setting up user interface\ngathering resources.");
    Container cont = getContentPane();
    System.out.println("loading tables");
    setTabs();
    readDatabase();
    readMisc();
    setCusTable();
    setLayouts();
    cont.add(tabs);  
    
  }

now lets say atm the database is created and there are no values in the table customer. so that mean when i do resultSet = select * from customer resultSet is still null.how do i cater on that.

read my answer again. I told you what you need to know.

ps: Did you previously code in Basic?

oopss i guesss u guys were right. i missed the declaration thats why it was working. and umm yeah i cant cast resultSet lol. can u tell me how to read the table into my hashtable.

can u tell me how to read the table into my hashtable.

Google can.

lol im already dea

thanks guys i managed to solve my problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.