Xpath 属性的 PreparedStatement

PreparedStatement for Xpath attribute

我有一个 xpath 查询。 xpath 中的值是动态填充的。

查询:

SELECT app_prof.pk_szid, app_prof.xmldata
FROM tblappprofile AS app_prof
WHERE 'Self' = 
CAST((xpath('/ApplicationProfile/ComponentIDs/ComponentID[@Family="Core"]/text()', xmldata))[1] AS TEXT)

准备好的语句:

SELECT app_prof.pk_szid, app_prof.xmldata
FROM tblappprofile AS app_prof
WHERE ? = 
CAST((xpath('/ApplicationProfile/ComponentIDs/ComponentID[@Family= ? ]/text()', xmldata))[1] AS TEXT)

当我使用时,

preparedStatement.setString(1, "Self");
preparedStatement.setString(2, "Core");

结果 org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1

'Self'填写正确。无法识别属性中的 ?。如何在 Xpath 中对属性使用 PreparedStatement

字符串文字中的问号不被视为参数占位符。

您需要将整个 XPath 表达式作为参数传递:

WHERE ? = CAST((xpath(?, xmldata))[1] AS TEXT)

另一种选择是使用 format() 函数动态创建字符串:

where ? = CAST((xpath(format('/ApplicationProfile/ComponentIDs/ComponentID[@Family="%s"]/text()',?), xmldata))[1]

这样您就可以将 @Familiy 的值作为参数传递,并且如果需要,仍将 XPath 保留在 SQL 中。