Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping hstore contains operators in a JDBC Prepared statement

I am using PostgreSQL 9.1.4 with hstore and the PostgreSQL JDBC driver (9.1-901.jdbc4).

I am trying to use the contains operators (?, ?&, ?|) in a PreparedStatement, however the ? character is parsed as a variable placeholder. Can this character be escaped to send the correct operator in the query?

An example:

PreparedStatement stmt = conn.prepareStatement("SELECT a, b FROM table1 WHERE c ? 'foo' AND d = ?");
stmt.setInt(1, dValue);
stmt.executeQuery();

In this form the following example would raise an exception:

org.postgresql.util.PSQLException: No value specified for parameter 2.

Update:

After investigating the query parser in the pgjdbc driver this snippet seems to indicate that it is not possible to escape the ? character. The questions that remain are:

  • Is there anything in the JDBC spec which allows a ? to be escaped and be anything other than a parameter placeholder?
  • Is there any better work around for this issue than just using plain Statements with variables manually inserted into the query string?
like image 223
Sam Macbeth Avatar asked Aug 13 '12 18:08

Sam Macbeth


People also ask

What is the return type of the Hstore function keys Hstore?

This module implements the hstore data type for storing sets of key/value pairs within a single PostgreSQL value. This can be useful in various scenarios, such as rows with many attributes that are rarely examined, or semi-structured data. Keys and values are simply text strings.

What is Hstore datatype?

The hstore module implements the hstore data type for storing key-value pairs in a single value. The hstore data type is very useful in many cases, such as semi-structured data or rows with many attributes that are rarely queried. Notice that keys and values are just text strings only.

What is Hstore extension?

hstore is a PostgreSQL extension that implements the hstore data type. It's a key-value data type for PostgreSQL that's been around since before JSON and JSONB data types were added.

What is Hstore column?

The hstore module is used to implement the hstore data type in the form of key-value pairs for a single value within PostgreSQL. The hstore data type is remarkably effective in many cases, such as, multiple rows with multiple attributes which are rarely queried for or semi-structured data.


1 Answers

Effectively, it looks like the java SQL parser is not hstore compliant.

But since the syntax c ? 'foo' is equivalent to exist(c, 'foo'), you can easily workaround this problem. Have a look at the following page to see what the verbose operators for hstore are.

Postgres hstore documentation

like image 127
aymeric Avatar answered Oct 23 '22 05:10

aymeric