无法在JDBC PreparedStatement上的单引号内转义参数

时间:2014-07-30 08:38:56

标签: java sql jdbc binding

我想通过JDBC进行这样的查询(注意它包含一些postgis函数):

SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category 
FROM pois 
WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(-5.8340534 43.3581991)'), 1000000);

所以我将查询参数化为:

SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category 
FROM pois 
WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(? ?)'), ?);

问题在于,在执行preparedStament时,它无法找到前两个参数,因为它们在单引号内,因此会出错。

我还试图用\“#39;没有成功:

SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category 
FROM pois 
WHERE ST_DWithin(location, ST_GeographyFromText(\'SRID=4326;POINT(? ?)\'), ?);

目前,作为一种解决方法,我没有绑定参数,只是将查询字符串附加到它们,但是它们容易受到SQL注入,所以我只想知道是否有任何方法逃避那句话使参数绑定工作。

2 个答案:

答案 0 :(得分:6)

问我自己,我使用字符串concat:

"SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category 
FROM pois 
WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(' || ? || ' ' || ? || ')'), ?);"

答案 1 :(得分:0)

作为一个天真的答案......

您可以在查询之前分配参数,然后将其与Query连接 例如:

Scanner scan = new Scanner(System.in); //don't forget to import java.util package
String par1 = scan.nextLine();
String par2 = scan.nextLine();

后来

String query = "SELECT id, name, ST_Y(location::geometry) as latitude, " + 
    "ST_X(location::geometry) as longitude, category_group, category " +
    "FROM pois " +
    "WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT("+par1+" "+par2+")'), ?)"; 

现在将此查询传递给查询创建语句