quick and dirty SQL string escaping

一曲冷凌霜 提交于 2019-12-05 22:17:16

For "quick and dirty" escaping, doubling the apostrophes is good enough. Be aware of question marks already inside string literals, though:

SELECT column FROM table WHERE column = 'A question?' or column = ?

You don't want to replace the first question mark. Also, these corner-cases should be taken care of:

SELECT /* Is this a comment?? */ * FROM table
-- -- --  Another comment??
WHERE column = ?

There's only one bind value in that statement. For a less quick-and-dirty solution, you could use a library like jOOQ for this problem, though (disclaimer: I work for the company behind jOOQ). It'll do the inlining for you, also for the more nasty data types:

DSLContext ctx = DSL.using(SQLDialect.POSTGRES);
Object[] bindValues = { 1, "a'bc", Date.valueOf("2012-09-24"), "xy".getBytes() };
String string = ctx.query(
  "SELECT 1 WHERE A = ? AND B = ? AND C = ? AND D = ?",
  bindValues).toString();

The above will render

SELECT 1 
WHERE A = 1 
AND B = 'a''bc'
AND C = date '2012-09-24' 
AND D = E'\\170\\171::bytea

If you're not averse to using a 3rd-party open source library, then I'd say take a look at Apache Commons Lang's StringEscapeUtils.escapeSql(String str).

EDIT: I just checked the source. It does nothing more than replace a single quote (') with two single quotes ('') as you do.

Maybe you can give a look at the escapeJava(String input) from Apache's StringEscapeUtils.

public static final String escapeJava(String input)

Escapes the characters in a String using Java String rules.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!