user3198552
user3198552

Reputation: 21

Java PreparedStatement nullPointerException

I have two classes, in the first one I declare my connection to the derby database

       static final String DATABASE_URL = "jdbc:derby://localhost:1527/A3";
        Connection conn = null;
       public ConnectionToSql() throws ClassNotFoundException  {
       try {       
        conn = DriverManager.getConnection(
                DATABASE_URL, "root", "1234" );
         } catch (SQLException e) {
         }

and in my second class I use a preparedStatement

       public String validateUser(String username, String password) {

        try {
              PreparedStatement ps = (PreparedStatement) conn.prepareStatement("SELECT *        FROM       users where username = ? and password = ?");

          ps.setObject(1, username);
          ps.setObject(2, password);

          ResultSet rs = ps.executeQuery();

and I get: Exception in thread "Thread-0" java.lang.NullPointerException at Server.SqlRepository.validateUser(SqlRepository.java:28)

Line 28 is the line with the prepared statement. Sorry about formatting.

Upvotes: 0

Views: 3915

Answers (2)

Rudi Kershaw
Rudi Kershaw

Reputation: 12972

If your connection is being instantiated in the other class how have you moved a reference to it to the class to create the prepared statement? Also, if you are moving the reference to your second class correctly, how can you be sure your DriverManager.getConnection() returned a valid connection or didn't throw an Exception?

Clearly, conn is either not instantiated or is referencing null.

try {       
    conn = DriverManager.getConnection(
            DATABASE_URL, "root", "1234" );
    } catch (SQLException e) {
        // You are doing nothing if the statement in your try block throws an exception.
    }

In the above code you are doing what is called swallowing an Exception, which means that if the exception happens nothing is done about it. At the very least you could add e.printStackTrace(); into the catch block so you can see in the console when an Exception is thrown.

If getConnection() throws an Exception in your current code, then when you call conn.prepareStatement(), conn will be null hence the NullPointerException. I hope this helps.

For Reference;

Upvotes: 1

MTilsted
MTilsted

Reputation: 5545

Most likely reason: DriverManager.getConnection throws an exception which you then shallow. In that case conn will be null.

Upvotes: 0

Related Questions