gpt4 book ai didi

java - JDBCPreparedStatement 中的 PostgreSQL query_to_xml

转载 作者:行者123 更新时间:2023-12-01 09:56:13 29 4
gpt4 key购买 nike

这个问题与 Using query_to_xml in PostgreSQL with prepared statements 非常相似但是那里的解决方案似乎不适用于我的情况。这实际上是一个非常奇怪的情况。我有以下查询,效果很好。

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

和准备好的声明,例如:

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

但是,如果我向查询添加另一个字符串参数,则会引发错误。例如;

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();

抛出以下错误:

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

我将字符串“c”定义为单词“percent”。我认为这个问题实际上是因为它是我传递到查询中的字符串。我还尝试将百分比一词硬编码到我的 where 子句中,并且不将其作为参数包含在准备好的语句中,如下所示;

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

但这会给出以下错误;

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

我猜解决方案可能是需要添加或删除某个地方的单引号或双引号,但我似乎看不到它。

最佳答案

这是查询中的查询。所以它需要在引号内包含引号。为此,内部引号应该加倍:

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

SQL 文字 ' and col6 = ''' 将在服务器端解释为 and col6 = ', and '''' 将被解释为 ',因此字符串的每一侧都会有一个引号,这是您需要告诉内部查询这是一个字符串.

关于java - JDBCPreparedStatement 中的 PostgreSQL query_to_xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37188457/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com