Search code examples
javasql-serverjdbcresultset

Java + SQL Server: Resultset is null?


I am new to using java with a database and I have been trying following code:

public int getDateDiff(int OrderID) {
    Connection conn = DBConnection.getConnection();
    Integer diff = null;
    String getdiffSQL = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ?;";
    try {
        PreparedStatement pstm = conn.prepareStatement(getdiffSQL); 
        pstm.setInt(1, OrderID);
        ResultSet rs = pstm.executeQuery(getdiffSQL);
            while (rs.next()) {
                diff = rs.getInt(1);
            }
        }
     catch (SQLException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
    return diff;
}

I tried running this but i encounter this

"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"

and the the return diff is null. Please tell me what wrong in this and how do i fix this.


Solution

  • PreparedStatement#executeQuery() does not take a parameter and you should not be passing the query string. Instead use this pattern:

    PreparedStatement pstm = conn.prepareStatement(getdiffSQL); 
    pstm.setInt(1, OrderID);
    ResultSet rs = pstm.executeQuery();   // no parameter
    

    This is a fairly common mistake made when using JDBC, partly because Statement#executeQuery() does take the query string as a parameter. Add to this tutorials like MkYong which make the same mistake as the OP and it is easy to see why this error is so prevalant.