0

I'm new to the use of Java with database connections, but am getting a NullPointerException using the following code:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList; 

public ArrayList<UserVO> getAllUsers(Connection connection) throws Exception {
            ArrayList<UserVO> userList = new ArrayList<UserVO>();
            try {
                PreparedStatement ps = connection.prepareStatement("SELECT * FROM user");
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    UserVO uservo = new UserVO();
                    uservo.setUsername(rs.getString("username"));
                    uservo.setPassword(rs.getString("password"));
                    userList.add(uservo);
                }
                return userList;
            } catch (Exception e) {
            throw e;
            }
        }

    }

At

PreparedStatement ps = connection.prepareStatement("SELECT * FROM user");

the code throws an exception for java.lang.NullPointerException.I don't know why this is happening, as a

System.out.println("isClosed = " + connection.isClosed());

before the PreparedStatement declaration returns false, and I can print out the connection info.

Any idea of the cause or how to properly compose a statement before query execution? Thanks!

EDIT: Full(ish) stack trace - it's very long

java.lang.NullPointerException
    at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:649)
    at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:587)
    at com.mysql.jdbc.PreparedStatement.toString(PreparedStatement.java:4068)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuffer.append(StringBuffer.java:263)
    at com.mysql.jdbc.trace.Tracer.printParameters(Tracer.aj:240)
    at com.mysql.jdbc.trace.Tracer.printEntering(Tracer.aj:167)
    at com.mysql.jdbc.trace.Tracer.entry(Tracer.aj:126)
    at com.mysql.jdbc.trace.Tracer.ajc$before$com_mysql_jdbc_trace_Tracer$1$f51c62b8(Tracer.aj:45)
    at com.mysql.jdbc.Connection.registerStatement(Connection.java)
    at com.mysql.jdbc.Statement.<init>(Statement.java:270)
    at com.mysql.jdbc.PreparedStatement.<init>
Coleen
  • 124
  • 1
  • 13

0 Answers0