Re: JDBC ilikequery encounter some problems - Mailing list pgsql-jdbc

From David G. Johnston
Subject Re: JDBC ilikequery encounter some problems
Date
Msg-id CAKFQuwZejrjD5+--oHVNrFmUAse_S3iYmQidmj8fEpkgrThzsA@mail.gmail.com
Whole thread Raw
In response to JDBC ilikequery encounter some problems  (Jian He <hejian.mark@gmail.com>)
List pgsql-jdbc
On Sun, Jun 20, 2021 at 10:18 PM Jian He <hejian.mark@gmail.com> wrote:
--------------- not working
String ilikequery = "SELECT * FROM emp where ? iLIKE '%C%' ";
PreparedStatement ilikestatement = Main.connection.prepareStatement(ilikequery);
ilikestatement.setString(1,"name");
ResultSet resultSet = ilikestatement.executeQuery();

Has nothing to do with the iLIKE operator - identifiers cannot be parameterized.  You need to decide on a different way to get the column "name" into the query string safely.

------------this one not working.

String ilikequerywithparameter = "SELECT * FROM emp" + " where name iLIKE '%"+"?"+"%' ";
PreparedStatement ilikestatementpara = Main.connection.prepareStatement(ilikequerywithparameter); ilikestatementpara.setString(1,"c"); ResultSet resultSet = ilikestatementpara.executeQuery();

The last code snippet have Exception error.Exception in thread "main" org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns:

You put the question mark inside single quotes in the submitted query and thus as far as the system is concerned it is just a string containing a question mark, not a parameter symbol.  The direct way to make it work is to add string concatenation operators between the literal parts (which are quoted) and the parameter (which is not), having the server build the final string from the three individual parts.

David J.

pgsql-jdbc by date:

Previous
From: Jian He
Date:
Subject: JDBC ilikequery encounter some problems
Next
From: Dave Cramer
Date:
Subject: [pgjdbc/pgjdbc]