Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several close placeholders in postgres prepared statement

I'm using Spring JbdcTemplate with Postgres.

Stuck with a problem cause of the Postrgres JDBC internal prepared statement implemetation

My query string is:

private static final String SELECT_ALL_PARTIALLY =
            "SELECT login, added FROM admin ORDER BY ? ? OFFSET ? LIMIT ?";

And I want to use it like:

List matches = getJdbcTemplate().query(SELECT_ALL_PARTIALLY,
                (new Object[]{
                    column, // "login" or "added"
                    order,  // "asc" or "desc"
                    offset, 
                    limit
                }),
                new RowMapper() {
                    ...

The problem is with a ...ORDER BY ? ? OFFSET...

org.postgresql.util.PSQLException: ERROR: syntax error at or near "$2"
  Position: 61
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:273)
    at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:648) ...

How can I separate this two placeholders or something?

like image 876
user976426 Avatar asked Jun 30 '26 06:06

user976426


1 Answers

Postgres doesn't allow you to specify ordering direction as a parameter. You need to create different query strings for asc and desc order and choose one of them to execute.

like image 92
axtavt Avatar answered Jul 01 '26 20:07

axtavt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!