代码之家  ›  专栏  ›  技术社区  ›  siva636

如何区分MySQL中INT列中的0和null

  •  4
  • siva636  · 技术社区  · 14 年前

    如果MySQL INT列中存储了一个空值,那么当JPA等技术人员访问它时,它将返回0。如果列中还存储了0值,如何区分null和0?

    3 回复  |  直到 14 年前
        1
  •  5
  •   foret    14 年前

    我真不敢相信,事情就是这样。
    更改实体中对象类型的基元类型(例如:int->Integer)

        2
  •  2
  •   Barmaley    14 年前

    若要区分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();
    }
    
        3
  •  1
  •   user3400705    10 年前

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