JDBC和Oracle DB:Escape' (单引号)

时间:2016-07-19 12:12:26

标签: java jdbc escaping quote

您好,这看起来很简单,但我在这里遇到问题。

首先,我使用Statement#executeBatch来执行许多UPDATE语句。每个更新语句都有要更新的String值。这些字符串有" ' "单引号。我已经尝试按照Oracle doc添加一个单引号,并添加' \\\'在单引号前面。使用第一个,我的查询卡住了,即使在10分钟后也不会出现。第二个我得到了批处理:ORA-00927:缺少等号'错误。

什么是正确的方法? 注意: - 我不能使用PreparedStatement来使用JDBC参数。

请帮忙。

1 个答案:

答案 0 :(得分:3)

您可以使用q-quoted strin g例如q'['''''''']'

这给出了以下示例

Statement stmt = con.createStatement();

stmt.addBatch("update tst set txt = q'['''''''']' where id = 1");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 2");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 3");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 4");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 5"); 
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();

正确方式是使用预准备语句

PreparedStatement stmt = con.prepareStatement("update tst set txt = ? where id = ?");
5.times { i ->
  stmt.setString(1, "''''''''");
  stmt.setInt(2, i+1);
  stmt.addBatch();
}

// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();