当数据库中为null时,整数变量为零

Jåc*_*cob 0 java integer jdbc

我已将变量声明为

private Integer projectId;

   public void setProjectId(Integer projectId) {
    this.projectId= projectId;
}

public Integer getProjectId() {
    return projectId;
}
Run Code Online (Sandbox Code Playgroud)

从数据库中检索值时,如果projectId在数据库表中为空,则显示为0例如

log.info("?? "+projectList.get(1).getProjectId());
Run Code Online (Sandbox Code Playgroud)

以上的结果是0.

为什么它显示为0虽然它在桌子空,我怎么能做出这是null当它是null在表中?

编辑1

while (rs.next()) {
projectList.add(mapProjects(resultSet));

}

private static Project mapProjects(ResultSet rs) 
throws SQLException {
return new Project ((rs.getInt("ID")), 
(rs.getInt("PROJECT_ID")), 
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 10

你必须亲自处理这个案子.该ResultSet文件明确指出(重点煤矿):

getInt int getInt(int columnIndex)

以Java编程语言中int的形式检索此ResultSet对象的当前行中指定列的值.

参数:
*columnIndex - 第一列是1,第二列是2,...

返回:
列值; 如果值为SQL NULL,则返回的值为0

您必须wasNull()在读取列值后调用并将字段设置为null是否是这种情况.如下所示:

Integer projectId = rs.getInt("PROJECT_ID");
if (rs.wasNull()) projectId = null;
return new Project (rs.getInt("ID"), projectId), ...);
Run Code Online (Sandbox Code Playgroud)

出于理智原因,如果将代码移动到新方法中,则可能更好:

/**
 * Retrieves the value from the designated column as an {@link Integer}
 * object.
 * 
 * @param rs
 *            The ResultSet to read from.
 * @param columnName
 *            The column name to read.
 * @return {@code null} if the column value was SQL NULL; its value as an
 *         integer otherwise.
 */
public static Integer getInteger(ResultSet rs, String columnName) {
    int v = rs.getInt(columnName);
    return rs.wasNull() ? null : v;
}
Run Code Online (Sandbox Code Playgroud)

  • 这有点烦人,因为你*首先*必须检索值然后*然后*检查`NULL`(这使得条件运算符在这里没用).我添加了一些代码. (2认同)