0

Can anyone tell me what I'm doing wrong? I have a database with a table called henry_author that looks like this:

Table Name: henry_author
| author_num | author |
-----------------------
| 0          | james  |
| 1          | jack   |

I'm trying to get both the numbers from the henry_author table.

Here is what I'm doing:

public static void main(String[] args) throws Exception {
    Connection conn = null;
    PreparedStatement pstmt = null;
    Statement stmt = null;

    try {
        conn = getConnection(); // this is basically the DB_URL, USER, PASS and DriverManager.getConnection() method/function I made
        String query = "SELECT author_num FROM henry_author";
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            int number = rs.getInt("author_num");
            System.out.println("Author num: + number);
        }
     } catch (SQLException sqle) {
         sqle.printStackTrace();
     }
 }

I keep getting the error: java.lang.NullPointerException. No clue on what is wrong with the code.

James
  • 21
  • 1
  • You forgot to create a Statement. – Eran Dec 08 '16 at 09:03
  • @Eran Huh? Sorry. Super new to JDBC. Just started playing around with it a few hours ago. – James Dec 08 '16 at 09:05
  • Add `stmt = conn.createStatement();` before `stmt.executeQuery(query)`. – Eran Dec 08 '16 at 09:06
  • @Eran Wow. Thanks! – James Dec 08 '16 at 09:07
  • eran is right. you write `Statement stmt = null;` but never create a new one. thats why you get NPE – XtremeBaumer Dec 08 '16 at 09:07
  • 1
    Note that if you hadn't initialized your local variables to `null` for no good reason, you'd have received an error at *compile-time* instead of an exception. It's not clear why you've declared those variables outside the try block at all. – Jon Skeet Dec 08 '16 at 09:08
  • @JonSkeet Is it good practice not to initialize them outside like that? – James Dec 08 '16 at 09:09
  • 1
    Nope, in general you should give your variables the least scope possible, and avoid providing pointless values. Ideally, initialize at point of first use, e.g. `Connection conn = getConnection()`. – Jon Skeet Dec 08 '16 at 09:10
  • @JonSkeet Thank you so much for your insight! – James Dec 08 '16 at 09:13

0 Answers0