简体   繁体   中英

Parameterized query in PostgreSQL

I am new in PostgreSQL and trying to get parameterized query to work. I have following sql statements where type A seems to be ok but type B does not work.

sql type A)

 StringBuilder buffer = new StringBuilder("Select * from JOB where")    
 buffer.append(" START_TIME ");
 buffer.append(" BETWEEN '2020-08-17' AND '2020-08-18'");
 String sql = buffer.toString();

sql type B) - parameterized

 StringBuilder buffer = new StringBuilder("Select * from DA_JOB where")    
 buffer.append("START_TIME");
 buffer.append(" BETWEEN ? AND ?");
 String sql = buffer.toString();

execute query based on the type - executing type A is successful but type B is not

try (Connection dbConnection = getConnection();
     PreparedStatement statement = dbConnection.prepareStatement(sql)) {
      if (typeB) {
             //myHashMap<String, String> holds some key value

              StringBuilder st = new StringBuilder("'");
              String value = myHashMap.get("startTime")
              st.append(value);
              st.append("'");
              statement.setString(1, st.toString());                
              
              StringBuilder st1 = new StringBuilder("'");
              String value2 = myHashMap.get("endTime")
              st1.append("'");
              statement.setString(2, st1.toString());
      }
      try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
                 jobs.add(sanitize(rs));
             }
        } 

 }

the error I get from executing parameterized query which is type B is

"org.postgresql.util.PSQLException: ERROR: operator does not exist: timestamp without time zone >= character varying\n Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

which seams to be quotation problem in the final query after setting string. Any tips on how I can fix this? It is really appriciated.

Basically, the problem is that the DB engine is refusing to cast your string into a date. There are two approaches you can take to fix this. One is to add a cast server-side. BETWEEN?::date AND?::date should work. The :: is a PostgreSQL non-standard cast; you can also use SQL-compliant CAST syntax if you want.

An alternative would be to use preparedStatement's setDate , creating a java.sql.Date object from your stored String (or storing a Date in your HashMap).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM