运行环境
Oracle 9i, Oracle JDBC driver ojdbc14.jar
本文发现
如果用固定长度字段, 在用PreparedStatement.setString(int, String)设值的时候, 需要用空格在右边补位, 否则判为不等. 直接用字符串拼接sql不存在这个问题.
案例
假设有表
hello001(id, fix_id), id: nvarchar(20), fix_id: char(10)
并且已经插入一条记录
insert into allcomments.hello001(id, fix_id) values ('nihao', 'nihao')
通过JDBC删除这条记录, 有两种方式: 一是用PreparedStatement, 二是用Statement
PreparedStatement 方式:
Connection conn = DatabaseConn.getConnection();
String sql = "delete from hello001 where fix_id = ?";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
// ps.setString(1, "nihao ");//这样才能能删除记录, 需要用空格补足位数
ps.setString(1, "nihao");//这样是不可以的
ps.executeUpdate();
} catch (SQLException e) {
...
} finally {
...
}
Statement 方式:
Connection conn = DatabaseConn.getConnection();
String sql = "delete from hello001 where comment_id = 'nihao'";
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
...
} finally {
...
}
}
如果用Statement, 因为是拼字串, 和上面的拼字串方式一样, 可以删除记录.
但直接通过PL/SQL Developer执行
delete from hello001 where fix_id='nihao '
和
delete from hello001 where fix_id='nihao'
效果一样, 右侧空格智能处理.
TODO:
有关数据右侧有空格的问题, 还需要关注插入的情况.
分: 数据右侧有空格, 数据格式是定长和可变长度.
写了一个工具类, 字串变长, 但是否适用于mysql, 有待验证.