title: How do I escape a literal question mark ('?') in a JDBC prepared statement
body: <p>I'd like to create a JDBC PreparedStatement like:</p>
  
  <pre><code>SELECT URL,LOCATE ( '?', URL ) pos FROM Links WHERE pageId=? ORDER BY pos ASC
  </code></pre>
  
  <p>Where the 1st <code>?</code> is a literal and the 2nd <code>?</code> is a parameter.  I could use <code>CHAR(63)</code> in place of the <code>'?'</code> but I think the extra function call would slow down the SQL execution. Is there some way to escape that 1st <code>?</code>?</p>
  
  <p>Edit:</p>
  
  <p>The following code tests dkatzel's assertion that the <code>?</code> character in a string is not considered a marker:</p>
  
  <pre><code>public class Test {
      public static void main(String[] args) throws SQLException {
          Connection conn = DriverManager.getConnection("jdbc:h2:mem:test");
          Statement stmt = conn.createStatement();
          stmt.executeUpdate("CREATE TABLE Links(URL VARCHAR(255) PRIMARY KEY,pageId BIGINT)");
          stmt.executeUpdate("INSERT INTO Links(URL,pageId) VALUES('http://foo.bar?baz',1)");
          stmt.executeUpdate("INSERT INTO Links(URL,pageId) VALUES('http://foo.bar/baz',1)");
          stmt.close();
          PreparedStatement ps = conn
              .prepareStatement("SELECT URL,LOCATE ( '?', URL ) pos FROM Links WHERE pageId=? ORDER BY pos ASC");
           ps.setLong(1, 1);
          ResultSet rs = ps.executeQuery();
          while (rs.next()) {
              System.out.println(rs.getString(1) + ":" + rs.getInt(2));
          }
          rs.close();
          ps.close();
          conn.close();
      }
  }
  </code></pre>
  
  <p>The output:</p>
  
  <pre><code>http://foo.bar/baz:0
  http://foo.bar?baz:15
  </code></pre>
  
  <p>It appears that dkatzel is correct.  I searched the the <a href="http://download.oracle.com/otndocs/jcp/jdbc-4_1-mrel-spec/index.html" rel="noreferrer">JDBC Spec</a> and could not find any mention that the <code>?</code>  parameter marker would be ignored if it's within quotes, but the few implementations of PreparedStatement parsers that I found (<a href="http://www.docjar.com/html/api/com/mysql/jdbc/PreparedStatement.java.html" rel="noreferrer">MySql</a>,<a href="http://c-jdbc.ow2.org/current/doc/doxygen/english/html/PreparedStatement_8java-source.html" rel="noreferrer">c-JDBC</a>,<a href="http://h2database.googlecode.com/svn/trunk/h2/src/main/org/h2/command/Parser.java" rel="noreferrer">H2</a>) all appear to exclude text within single quotes from consideration as parameter markers.</p>