参数化查询:检查字段是否在 SELECT 语句中的值数组中
我正在尝试配置参数化查询,以达到以下效果:
SELECT field1 FROM myTable WHERE field2 IN (1,2,3,4)
我正在使用的数据库是 Postgres。
此查询成功运行,未参数化,但我想使用带有 JdbcTemplate 的参数化查询来填充有效 field2 值(整数)的列表。
尝试 var
的各种值 ("1,2,3,4"
, "[1,2,3,4]"
, < ) 我尝试过查询的变体:
myJdbcTemplate.query("SELECT field1 FROM field2 IN (?)", new Object[]{ var })
并且
myJdbcTemplate.query("SELECT field1 FROM field2 IN (?::integer[])", new Object[]{ var })
code>"{1,2,3,4}" 或 "(1,2,3,4)"
myJdbcTemplate.query("SELECT field1 FROM field2 IN ?::integer[]", new Object[]{ var })
另外,描述如何参数化查询的资源也非常有帮助。
所有这些查询都会抛出 PSQLException,表明运算符失败或存在类型不匹配——这似乎是合理的,因为我不知道如何参数化查询。
I'm trying to configure a parameterized query to the effect of:
SELECT field1 FROM myTable WHERE field2 IN (1,2,3,4)
The database I'm using is Postgres.
This query run successfully unparameterized, but I'd like to use a parameterized query with a JdbcTemplate to fill in the list for valid field2 values (which are integers).
Trying various values for var
("1,2,3,4"
, "[1,2,3,4]"
, "{1,2,3,4}"
, or "(1,2,3,4)"
) I've tried variations on the query:
myJdbcTemplate.query("SELECT field1 FROM field2 IN (?)", new Object[]{ var })
and
myJdbcTemplate.query("SELECT field1 FROM field2 IN (?::integer[])", new Object[]{ var })
and also
myJdbcTemplate.query("SELECT field1 FROM field2 IN ?::integer[]", new Object[]{ var })
On a side note, resources that describe how to parameterize queries would also be really helpful.
All of these queries throw PSQLExceptions that indicate the operator fails or that there's a type mismatch -- which seems reasonable as I can't figure out how to parameterize the query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 Spring 数据访问网页,特别是 11.7 节.3 其中使用 NamedParameterJdbcTemplate。
例如
Take a look at the Spring Data Access web page, particularly section 11.7.3 where using the NamedParameterJdbcTemplate to build an 'IN' clause is covered.
e.g.
我又看了一遍手册,它看起来像是搜索数组还有一种替代语法,例如:
可以参数化为:
I took another look at the manual, it looks like to search arrays there's an alternative syntax, something like:
Which can be parameterized as: