0

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.

user3198552
  • 21
  • 1
  • 2
  • Looks like you have a problem creating the connection. Please do never `catch (SQLException e) { }`. Add at least `e.printStacktrace()` between the `{}` so you can see if you have a problem. – Jens May 31 '14 at 11:02
  • You are ignoring exceptions when creating the connection. – Mark Rotteveel May 31 '14 at 11:02
  • Don't forget to upvote any answers you found helpful an accept an answer by clicking the greyed out tick. If none of the current answers solved your problem sufficiently you can post your own answer with how you solved your issue and accept that one. : ) – Rudi Kershaw Jun 11 '14 at 09:59

2 Answers2

1

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;

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
0

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

MTilsted
  • 5,425
  • 9
  • 44
  • 76