1

Ive been trying to validate values from Database.

so the scenario is,

if my

int id=1234;
    PreparedStatement st= null;
Connection con =null;
con=DriveManager.getConnection(//details here);
    String query ="SELECT ID FROM VAULT WHERE NUM=?";
    st= con.prepareStatement(query); <------ NULLPOINTEREXCEPTION
    st.setInt(1,id);
    rs=st.executeQuery();
    while(rs....)
    {
    String checker = rs.getString("ID");
    }
    if(checker.isEmpty() || checker ==null){
    ...//code here
    }

PROBLEM: how to handle and store NULL value on the String checker? how to retrieve NULL value to be used on validation?

Program is stopping on prepareStatement as it is getting NULLPOINTER Ps: the query is returning NULL actually, and i need that NULL value for checking. so If it is NULL, i will do INSERT to that table.

  • What is `con`? Is it `null`? –  Jul 22 '19 at 10:18
  • i have my connection established con=DriveManager.getConnection() etc etc – Jeannell Casaje Jul 22 '19 at 10:19
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – seenukarthi Jul 22 '19 at 10:19
  • 1
    `con` must be `null` – deHaar Jul 22 '19 at 10:20
  • If you're getting an NPE from `st= con.prepareStatement(query);`, then either `con` is `null` or `query` is `null` as of when you make that call. Given the code above, I'd say `con` is `null` because `DriveManager.getConnection()` (sic) is returning `null`. – T.J. Crowder Jul 22 '19 at 10:25
  • Side note: There's no purpose served by having `= null` initializers on your `st` and `con` declarations. In fact, it defeats a useful feature of the Java compiler (an error if you try to use an uninitialized variable). – T.J. Crowder Jul 22 '19 at 10:25
  • @T.J.Crowder the query is returning NULL actually, and i need that NULL value for checking. so If it is NULL, i will do INSERT to that table. – Jeannell Casaje Jul 22 '19 at 10:26
  • Side note 2: The `|| checker ==null` part of statement `if(checker.isEmpty() || checker ==null)` is in the wrong place. `||`'s operands are evaluated left to right. If `checker` is `null`, `checker.isEmpty()` will throw an NPE. It needs to be the other way around: `if(checker ==null || checker.isEmpty())`. `checker` is also inaccessible where you're using it (outside the `while`), because it's declared *inside* the `while`. I suggest stepping back from your current task and working through some basic Java tutorials and/or a good beginning Java book. – T.J. Crowder Jul 22 '19 at 10:28
  • 1
    @JeannellCasaje - No, if you're getting an NPE from the line you said you're getting it from, the query is not returning NULL. The query isn't running at all, because the code has already failed before the call to `executeQuery`. – T.J. Crowder Jul 22 '19 at 10:28
  • 1
    @T.J.Crowder got it. realized it. thank you – Jeannell Casaje Jul 22 '19 at 10:30

0 Answers0