尽量避免使用Oracle的char类型,即使只有一个字节,也应该使用varchar2类型。
char的缺点主要有两个
1.占用空间大
如果声明一个char(10)的字段,仅仅使用了一个字节,剩余的9个字节也会使用空格补齐。
![](//img.blog.itpub.net/blog/attachment/201401/21/29254281_13902337023J86.png?x-oss-process=style/bb)
2.在JAVA程序中造成隐患
在下面最常用的JDBC中,查询一个char类型的字段,却查不到任何结果.
所以正确的查询语句应该是:
select id from a where trim(id)=?
或者
select id from a where id=rpad(?,10)
即使使用了这两个正确的SQL,也会带来性能问题。
因为第一个SQL不会利用正常创建的索引,而且在复杂的查询下,更容易出错。
所以还是忘了Oracle有char这个类型吧。
char的缺点主要有两个
1.占用空间大
如果声明一个char(10)的字段,仅仅使用了一个字节,剩余的9个字节也会使用空格补齐。
create table a
(
id char(10)
);
create table b
(
id varchar2(10)
);
insert into a values('test');
insert into b values('test');
commit;
(
id char(10)
);
create table b
(
id varchar2(10)
);
insert into a values('test');
insert into b values('test');
commit;
![](http://img.blog.itpub.net/blog/attachment/201401/21/29254281_13902337023J86.png?x-oss-process=style/bb)
2.在JAVA程序中造成隐患
在下面最常用的JDBC中,查询一个char类型的字段,却查不到任何结果.
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:127.0.0.1:1521:orcl", "edmond", "edmond");
PreparedStatement ps = connection.prepareStatement("select id from a where id=?");
ps.setString(1, "test");
ResultSet result = ps.executeQuery();
if (result.next()) {
System.out.println(result.getString(1));
} else {
System.out.println("没有任何记录");
}
result.close();
ps.close();
connection.close();
}
}
主要是因为char类型的字段,使用空格填充。public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:127.0.0.1:1521:orcl", "edmond", "edmond");
PreparedStatement ps = connection.prepareStatement("select id from a where id=?");
ps.setString(1, "test");
ResultSet result = ps.executeQuery();
if (result.next()) {
System.out.println(result.getString(1));
} else {
System.out.println("没有任何记录");
}
result.close();
ps.close();
connection.close();
}
}
所以正确的查询语句应该是:
select id from a where trim(id)=?
或者
select id from a where id=rpad(?,10)
即使使用了这两个正确的SQL,也会带来性能问题。
因为第一个SQL不会利用正常创建的索引,而且在复杂的查询下,更容易出错。
所以还是忘了Oracle有char这个类型吧。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29254281/viewspace-1073337/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29254281/viewspace-1073337/