How do I escape a literal question mark ('?') in a JDBC prepared statement

前端 未结 5 1837
醉酒成梦
醉酒成梦 2021-02-19 10:56

I\'d like to create a JDBC PreparedStatement like:

SELECT URL,LOCATE ( \'?\', URL ) pos FROM Links WHERE pageId=? ORDER BY pos ASC

Where the 1s

相关标签:
5条回答
  • 2021-02-19 11:24

    The meaning of the ? is specified in the SQL specification, and the JDBC specification defers to the SQL specification for this.

    A driver doesn't (and shouldn't) interpret a question mark in a literal as a parameter placeholder, as a question mark within a string literal is simply a character within the string literal. For more information look at chapter 5 of SQL:2011 Foundation (ISO-9075-2:2011).

    So escaping is not necessary (nor possible).

    0 讨论(0)
  • 2021-02-19 11:30

    Did you try it? I think quoted question marks are OK. only "bare" question marks should get replaced in the prepared statement

    0 讨论(0)
  • 2021-02-19 11:36

    If it doesn't work with your JDBC driver you could bind it as a String ?,

    ps.setString(1, "?");
    
    0 讨论(0)
  • 2021-02-19 11:43

    Depending on the JDBC driver you are using you may be able to escape by adding another question mark e.g. if you're using PostgreSQL

    https://jdbc.postgresql.org/documentation/head/statement.html

    In JDBC, the question mark (?) is the placeholder for the positional parameters of a PreparedStatement. There are, however, a number of PostgreSQL operators that contain a question mark. To keep such question marks in a SQL statement from being interpreted as positional parameters, use two question marks (??) as escape sequence. You can also use this escape sequence in a Statement, but that is not required. Specifically only in a Statement a single (?) can be used as an operator.

    0 讨论(0)
  • 2021-02-19 11:50

    I have used CHR(63) in my query and that helped resolving my issue.

    Here is what I did for example: select q'[<div id=['|"]TRD_%%GEN%%['|"].*]' || chr(63) || q'[</div>]' from dual;

    This helped getting the string as : <div id=['|"]TRD_%%GEN%%['|"].*?</div>

    I have then used this query inside the insert statement, and ran through PreparedStatement. Worked perfectly fine.

    The CHR function is an in built function and can be used similar to other oracle functions. You can use this if you know the query will not going to be repeated lots of times.

    0 讨论(0)
提交回复
热议问题