在Oracle中,我们为某一列设置默认值之后,插入数据有时候会出现值为空的想象,并没有赋默认值。
这是因为在insert数据的时候,如果该列不出现在insert语句中的时候,会为其赋上默认值.如果插入时候为该列设置"",null数据库并不会为改列设置默认值。
例子:如下面的表:
create table test(id number(10),name varchar2(20) default 'name')
当用下面的SQL语句插入行的时候,会给name列赋默认值.
insert into test(id) values(1)
查询结果为:select * from test
ID | NAME |
1 | name |
当用下面的SQL语句插入行的时候,不会给name列赋默认值.
insert into test values(2,null)
查询结果发现ID为2的行的name的值为空:select * from test
ID | NAME |
1 | name |
2 |
select * from test where name is null 能将ID为2的行查询出来.
同样,在通过JAVA代码用JDBC,一些ORM框架插入数据的时候,也需要注意同样的问题.
private static void testNULL() throws SQLException {
String sqlstr = "insert into test values(?,?)";
Connection conn = NONXADBUtil.getConnection("jdbc:oracle:thin:@xxx:orcl", "xxx", "xxx");
PreparedStatement sta = conn.prepareStatement(sqlstr);
sta.setInt(1, 3);
sta.setString(2, null);##1
sta.executeUpdate();
sta.close();
conn.commit();
conn.close();
}
上面的代码插入的行,name列也不会被赋值为默认值,将##1处改为sta.setString(2, "")同样插入的是空值(null).