抛出JDBC Null指针Exception

时间:2010-04-12 11:16:31

标签: java jdbc nullpointerexception

嗨我在rs.next()或rs.getString(1)上得到nullpointerexception 有时rs.next()工作正常并且在rs.getString(“PRODUCTCODE”)处抛出nullpointerexception,有时它会在rs.getString(“PRODDATE”)处抛出npe,这真的很奇怪 我不明白为什么当rs.next()工作正常时,rs.getString()会使npe失效

这是我的代码

{ 
ResultSet rs = null;
String query = "";
BarcodeBean bi = null;
try {
query = "SELECT * FROM TABLE(GET_BARCODEINFO('"barcode.trim()"'))";

statement = connection.createStatement();
Logger.getInstance().getLogger().logInfo(query);
rs = statement.executeQuery(query);

bi = new BarcodeBean();

if (rs == null){
if(rs.next()){

bi.setUrunKodu(rs.getString("PRODUCTCODE"));
bi.setImalatMakineKodu(rs.getString("PRODMACHINECODE")); 
bi.setOperatorSicilNo(rs.getString("OPERATORID")); 
bi.setImalatTarihi(rs.getString("PRODDATE")); 
bi.setImalatVardiyasi(rs.getString("PRODSHIFT"));
bi.setSeriNumarasi(rs.getString("SERIALNUMBER"));
bi.setSirtTarihi(rs.getString("SIRTTARIHI"));
}
}
} catch (SQLException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
} finally {

DatabaseUtility.close(rs);
DatabaseUtility.close(statement);

}
} 

4 个答案:

答案 0 :(得分:3)

可能你想要:

if (rs != null) {
   if (rs.next()) {

甚至更好:

if (rs != null && rs.next()) {

你的测试完全错了。

答案 1 :(得分:3)

Statement#executeQuery() 从不返回null。整个nullcheck是多余的。正常的习语如下:

public Entity find(Long id) throws SQLException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    Entity entity = null;

    try {
        connection = database.getConnection();
        preparedStatement = connection.prepareStatement(SQL_FIND);
        preparedStatement.setLong(1, id);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            entity = new Entity();
            entity.setId(resultSet.getLong("id"));
            entity.setName(resultSet.getString("name"));
            // ...
        }
    } finally {
        close(connection, preparedStatement, resultSet); // In reversed order.
    }

    return entity;
}

您的实际问题出在其他地方。这显然是对堆栈跟踪的误解。要正确地确定它,你需要查找堆栈跟踪中第一行的行号,并指出这个行号的确切代码。

答案 2 :(得分:2)

来自Statement javadocs

  

public ResultSet executeQuery(String sql)抛出SQLException

     

返回:一个ResultSet   包含所生成数据的对象   通过给定的查询; 永不归零

因此,您无需验证rs == null

进行结果集行的标准方法是:

while (rs.next ()) {
   doSmth (rs);
} 

答案 3 :(得分:0)

你在if条件中做了错误的符号,

所以改成它,     如果(RS!= NULL){      ......      .......}