Oracle JDBC 驱动程序对 CHAR
的处理有一个棘手的问题。数据类型。让我们来看这个简单的表格:
create table x (c char(4));
insert into x (c) values ('a'); -- inserts 'a '
所以当我在
CHAR(4)
中插入一些东西时,字符串总是用空格填充。当我执行这样的查询时也会这样做:select * from x where c = 'a'; -- selects 1 record
select * from x where c = 'a '; -- selects 1 record
select * from x where c = 'a '; -- selects 1 record
在这里,常数
'a'
也充满了空格。这就是为什么总是返回记录。当使用 JDBC PreparedStatement
执行这些查询时,情况就是如此。也是。现在棘手的是当我想使用绑定(bind)变量时:PreparedStatement stmt =
conn.prepareStatement("select * from x where c = ?");
stmt.setString(1, "a"); // This won't return any records
stmt.setString(1, "a "); // This will return a record
stmt.executeQuery();
这是一种解决方法:
PreparedStatement stmt =
conn.prepareStatement("select * from x where trim(c) = trim(?)");
stmt.setString(1, "a"); // This will return a record
stmt.setString(1, "a "); // This will return a record
stmt.executeQuery();
编辑 : 现在这些是约束:
c
的两个内容。和 ?
, 并且它使用 c
上的索引挺难的。 CHAR
移出至VARCHAR
(当然应该如此)是不可能的编辑 : 造成这些限制的原因是因为我是站在jOOQ 的开发者的角度来问这个问题的。 ,一个数据库抽象库。所以我的要求是提供一个非常通用的解决方案,它不会破坏 jOOQ 客户端代码中的任何内容。这就是为什么我不是这个解决方法的忠实粉丝。这就是为什么我无法访问
CHAR
列的声明。但是,我仍然希望能够处理这种情况。你会怎么做?处理
CHAR
的好习惯是什么?当我想忽略尾随空格时的数据类型?
最佳答案
如果你想
stmt.setString(1, "a"); // This won't return any records
要返回记录,请尝试
conn.prepareStatement("select * from x where c = cast(? as char(4))")
关于Oracle JDBC 和 Oracle CHAR 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5332845/