简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM