【问题标题】:How to differentiate between 0 and null in an INT column in MySQL如何区分 MySQL 的 INT 列中的 0 和 null
【发布时间】:2011-04-27 08:46:11
【问题描述】:

如果 MySQL INT 列中存储了一个空值,则在被 JPA 等技术访问时将返回 0。如果列中还存储了 0 值,如何区分 null 和 0?

【问题讨论】:

标签: java mysql database jpa


【解决方案1】:

我不敢相信,原来是这样。
更改实体中对象类型的原始类型(示例:int -> Integer)

【讨论】:

  • 你为什么不相信int不能容纳null
【解决方案2】:

要区分 0 和 NULL,您应该使用 ResultSet.wasNull() 方法,如下所示:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
public static void main(String[] args) throws Exception {    
Connection conn = getConnection();
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);

st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st.executeUpdate("insert into survey (id,name ) values (2,null)");
st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");

while (rs.next()) {
  String name = rs.getString(2);
  if (rs.wasNull()) {
    System.out.println("was NULL");
  } else {
    System.out.println("not NULL");
  }
}

rs.close();
st.close();
conn.close();
}

【讨论】:

  • OP 正在使用 JPA。那么就没有“原始” JDBC 的手段了。只需将int 更改为Integer 即可。
  • 我知道,但是原始 JDBC 有助于理解 null 和 0 之间的区别。
【解决方案3】:

我解决的方法如下:

Integer id;
Object o = rs.getObject("ID_COLUMN");
if(o!=null){
   id = (Integer) o;
} else {
   id = null;
}

【讨论】:

  • 这七行可以写成一行,而不会产生任何的区别:"Integer id=(Integer)rs.getObject("ID_COLUMN");"
猜你喜欢
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
相关资源
最近更新 更多