简体   繁体   中英

Rewriting SQL statements to prepared statements in Java

Due to circumstances outside our control (using code written by a 3rd party, in other words), we find ourselves needing to rewrite SQL statements with inline values into prepared statements. Right now, we're using a horrid set of regular expressions that catch most of the cases, but still fail on a few (and generally fail horribly, producing invalid SQL).

It's looking like we will need to actually parse the SQL, substituting "?" parameters for the explicit string and numeric values, and collecting the values for injection into the new prepared statement.

  1. Has anyone already done this?
  2. If you haven't, but you've used one of the Java SQL parsers, would you recommend that parser for this purpose?

Here's an example of the "hairier" sort of SQL we're dealing with and would like to rewrite:

rewrite from
SELECT COL1 FROM TB1 WHERE LOWER(COL2) = LOWER('foo bar ' || '&' || ' Abc(' || '''' || ')') 
    AND COL3 = 2 AND COL4 = 1
to
SELECT COL1 FROM TB1 WHERE LOWER(COL2) = LOWER(? || ? || ? || ? || ?) 
    AND COL3 = ? AND COL4 = ?
applied to ("foo bar ", "&", " Abc(", "'", ")", 2, 1)

1) You may create temproray table (session time, memory base - as you wish) to populate with values (right in lowercase for performance purpose) you need.

And change your query to:

SELECT  t1.COL1 
FROM    TB1 t1 
        INNER JOIN TEMP_TABLE t2 ON ( t2.val = LOWER(t1.COL2) )
WHERE   t1.COL3 = ? AND t1.COL4 = ?

2) If you are using MySQL and searched values doesn't contain comma you may use "find_in_set" function:

SELECT  COL1 
FROM    TB1 t1 
WHERE   FIND_IN_SET( LOWER(t1.COL2), ? )
        AND t1.COL3 = ? AND t1.COL4 = ?

applied to ("foo bar,&,Abc(,',)",2,1

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