Cannot use a LIKE query in a JDBC PreparedStatement?

前端 未结 7 1817
生来不讨喜
生来不讨喜 2020-12-01 06:11

The query code and query:

ps = conn.prepareStatement(\"select instance_id, ? from eam_measurement where resource_id in (select RESOURCE_ID from eam_res_grp_r         


        
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 06:43

    There are two problems with your statement. You have to understand how bind variables work. The query is not processed by substituing the characters ? with your parameters. Instead, the statement is compiled with placeholders and then, during execution, the actual values of the parameters are given to the DB.

    In other words, you parse the following query:

    SELECT instance_id, :p1
      FROM eam_measurement
     WHERE resource_id IN (SELECT RESOURCE_ID 
                             FROM eam_res_grp_res_map 
                            WHERE resource_group_id = :p2)
       AND DSN LIKE '?'
     ORDER BY 2
    

    I'm pretty sure the last parameter will be ignored because it is in a delimited character string. Even if it is not ignored, it does not make sense to have ' characters around because Oracle won't bind a parameter in a string (I'm surprised it hasn't raised any error, do you catch exceptions ?).

    Now if you replace your DNS LIKE '?' with DSN LIKE ? and bind "%Module=jvmRuntimeModule:freeMemory%" this will make sense and should return the correct rows.

    You still have the problem with your first parameter, it won't do what you expect, i-e the query that will be executed will be equivalent to the following query:

    SELECT instance_id, 'SUBSTR(DSN,27,16)'
      FROM ...
    

    which is not at all the same as

    SELECT instance_id, SUBSTR(DSN,27,16)
      FROM ...
    

    I would suggest parsing (=prepareStatement) the following query if you expect the SUBSTR to be dynamic:

    SELECT instance_id, SUBSTR(DSN,?,?)
      FROM eam_measurement
     WHERE resource_id IN (SELECT RESOURCE_ID 
                             FROM eam_res_grp_res_map 
                            WHERE resource_group_id = ?)
       AND DSN LIKE ?
     ORDER BY 2
    

提交回复
热议问题