使用 jdbctemplate 构建 sql 字符串的建议
我目前有这个:
MyObject myObject = getJdbcTemplate().queryForObject("select * from my_objects where id = ?",
new Object[]{new Integer(id)},
new MyObjectRowMapper());
现在在我的方法中我想传递一个枚举:
SortOrder.ASC
SortOrder.DESC
所以它将是:
ORDER BY ID ASC
或
ORDER BY ID DESC
所以在 sql 字符串中,我是否只需添加另一个“?”或者我是否必须建立这样的字符串:
"select * from abc ORDER BY ID " + sortOrder;
是否有首选方法?
I currently have this:
MyObject myObject = getJdbcTemplate().queryForObject("select * from my_objects where id = ?",
new Object[]{new Integer(id)},
new MyObjectRowMapper());
Now in my method I want to pass an enumeration:
SortOrder.ASC
SortOrder.DESC
So it will either be:
ORDER BY ID ASC
or
ORDER BY ID DESC
So inside the sql string, do I just add another '?' or do I have to build up the string like:
"select * from abc ORDER BY ID " + sortOrder;
Is there a preferred way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你必须使用第二种方法。准备好的语句不仅仅是“用我传递的字符串查询替换占位符”。所有参数都必须输入值才能插入到查询生成的语法树中。您不能将查询的一部分作为参数传递。
You have to use the second way. A prepared statement isn't just a "query-replace placeholders by the String I pass". All parameters must be typed values to insert into the syntax tree generated from the query. You can't pass a portion of a query as a parameter.
您无法更改
PreparedStatements
中的查询,因此您无法使用 ?对于asc
或desc
。我认为串联是您可以使用的最简单的方法。You can not change the query in
PreparedStatements
so you can not use ? forasc
ordesc
. I think concatenation is the simplest way you can use.