简体   繁体   English

JDBC PreparedStatement中的PostgreSQL query_to_xml

[英]PostgreSQL query_to_xml in JDBC PreparedStatement

This question is very similar to Using query_to_xml in PostgreSQL with prepared statements however the solution there doesn't seem to be working in my case. 这个问题与在带预准备语句的PostgreSQL中使用query_to_xml非常相似,但是在我看来,该解决方案似乎不起作用。 It's actually a very odd situation. 这实际上是一个非常奇怪的情况。 I have the following query which works fine. 我有以下查询,它工作正常。

String sql = "select query_to_xml('select col1,col2,col3 FROM table where col4 = '||?||' and col5 = '||?||'', true,true,'');";

and Prepared Statement like: 和准备好的声明,例如:

PreparedStatement ps0 = conn.prepareStatement(sql);
ps0.setInt(1, a);
ps0.setInt(2, b);
ResultSet rs0 = ps0.executeQuery();

However if I add another string parameter to the query it throws an error. 但是,如果我向查询添加另一个字符串参数,则会引发错误。 For example; 例如;

String sql = "select query_to_xml('select col1,col2,col3 FROM table where col4 = '||?||' and col5 = '||?||' and col6 = '||?||'', true,true,'');";

PreparedStatement ps0 = conn.prepareStatement(sql);
ps0.setInt(1, a);
ps0.setInt(2, b);
ps0.setString(3, c);
ResultSet rs0 = ps0.executeQuery();

Throws the following error: 引发以下错误:

org.postgresql.util.PSQLException: ERROR: column "percent" does not exist

Where I had defined my string "c" as the word "percent". 我将字符串“ c”定义为“百分比”的位置。 I assume this issue is actually because it is a string I'm passing into the query. 我认为这个问题实际上是因为它是我要传递给查询的字符串。 I also tried hard coding the word percent into my where clause and not including it as a parameter in the prepared statement as follows; 我还尝试将%单词硬编码到我的where子句中,并且不将其作为参数包含在准备好的语句中,如下所示;

String sql = "select query_to_xml('select col1,col2,col3 FROM table where col4 = '||?||' and col5 = '||?||' and col6 = 'percent'', true,true,'');"; 

but that gives the following error instead; 但这会产生以下错误;

org.postgresql.util.PSQLException: ERROR: syntax error at or near "percent"

I'm guessing the solution is probably down to a single or double quote somewhere that needs to be added or removed, but I can't seem to see it. 我猜测解决方案可能是需要添加或删除的某个地方的单引号或双引号,但我似乎看不到它。

It's a query inside a query. 这是查询内部的查询。 So it needs to have quotes inside quotes. 因此,它需要在引号内包含引号。 And for this to work, the internal quotes should be doubled : 为此,内部引号应加倍

String sql = "select query_to_xml('select col1,col2,col3 FROM table where col4 = '||?||' and col5 = '||?||' and col6 = '''||?||'''', true,true,'');";

The SQL literal ' and col6 = ''' is going to be interpreted on the server side as and col6 = ' , and '''' is going to be interpreted as ' , thus you'll have a quote on each side of the string, which is what you need in order to tell the internal query that this is a string. SQL文字' and col6 = '''将在服务器端被解释为and col6 = ' ,而''''将被解释为' ,因此,在服务器的每一侧都有一个引号字符串,这是告诉内部查询这是一个字符串所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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