我想知道如果单击搜索按钮后ID不存在,我在哪里输入命令以显示错误。。
else if(e.getSource() == btnSearch) {
ResultSet rs = null;
rs = sD.getSummonID(txtSummonID.getText());
Summon s = null;
try {
while(rs.next()) {
s = new Summon(rs.getInt("id"), rs.getString("plateNum"),
rs.getDouble("amount"), rs.getString("recDate"),
rs.getString("location"), rs.getString("officer"));
}
txtcarLicenceNo.setText(s.getCarLicenceNo());
txtAmount.setText(Double.toString(s.getAmount()));
txtLocation.setText(s.getLocation());
txtOfficer.setText(s.getOfficerInCharge());
} catch (SQLException ex) {
System.err.println("SQL Exception: " + ex);
}
}
另一类看起来像这个
public ResultSet getSummonID(String summonID) {
getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM record WHERE id = " + summonID);
return rs;
} catch (SQLException e) {
System.err.println("SQL Exception: " + e);
return rs;
}
}
rs = sD.getSummonID(txtSummonID.getText());
if(condition to check that your id is null) {
//display pop up
JOptionPane.showMessageDialog(frame, "Id does not exists");
}else {
// proceed further
Summon s = null;
try {
while(rs.next())
{s = new Summon(rs.getInt("id"), rs.getString("plateNum"),
rs.getDouble("amount"), rs.getString("recDate"),
rs.getString("location"), rs.getString("officer"));
}
txtcarLicenceNo.setText(s.getCarLicenceNo());
txtAmount.setText(Double.toString(s.getAmount()));
txtLocation.setText(s.getLocation());
txtOfficer.setText(s.getOfficerInCharge());
}
catch (SQLException ex)
{
System.err.println("SQL Exception: " + ex);
}
}
使用当前代码,当由于Summon对象s初始化为null而没有结果提取时,您将获得NullPointerException
:
Summon s = null;
并且当没有结果时
while(rs.next())
永远不会迭代来设置s
对象。为了避免空指针异常,您可以引入这里提到的空检查:
while(rs.next())
{s = new Summon(rs.getInt("id"), rs.getString("plateNum"),
rs.getDouble("amount"), rs.getString("recDate"),
rs.getString("location"), rs.getString("officer"));
}
if(s != null) {
txtcarLicenceNo.setText(s.getCarLicenceNo());
txtAmount.setText(Double.toString(s.getAmount()));
txtLocation.setText(s.getLocation());
txtOfficer.setText(s.getOfficerInCharge());
} else {
// display JOptionPane
JOptionPane.showMessageDialog(frame, "Your error/info message");
}
}