Java 在 JDBC 准备好的语句中使用变量而不是参数索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1097855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a variable instead of a parameter index with a JDBC prepared statement
提问by Zardoz
In many programming languages something like this is possible for prepared statements:
在许多编程语言中,对于准备好的语句来说,这样的事情是可能的:
PreparedStatement statement = connection.prepareStatement(
"SELECT id FROM Company WHERE name LIKE ${name}");
statement.setString("name", "IBM");
But not with java.sql.PreparedStatement. In Java one has to use parameter indices:
但不是 java.sql.PreparedStatement。在 Java 中,必须使用参数索引:
PreparedStatement statement = connection.prepareStatement(
"SELECT id FROM Company WHERE name LIKE ?");
statement.setString(1, "IBM");
Is there a solution to work with string variables like in the first example? Is "${.*}" not used somewhere else in the SQL language, or are there any conflicts? Cause then I would implement it by myself (parsing the SQL string and replacing every variable by "?" and then doing it the Java way).
有没有像第一个示例中那样使用字符串变量的解决方案?"${.*}" 是不是在 SQL 语言的其他地方没有使用,或者是否有任何冲突?因为然后我会自己实现它(解析 SQL 字符串并用“?”替换每个变量,然后以 Java 方式执行)。
Regards, Kai
问候, 凯
采纳答案by Zardoz
As kd304 mentioned in the comment to my posting, this is a very nice solution if you don't want to incorporate another 3rd party library (like Spring) into your project: Javaworld Article: Named Parameters for PreparedStatement
正如我的帖子的评论中提到的 kd304,如果您不想将另一个 3rd 方库(如 Spring)合并到您的项目中,这是一个非常好的解决方案:Javaworld 文章:PreparedStatement 的命名参数
回答by skaffman
Using a raw PreparedStatement, this is not possible, as you say. It is possible with CallableStatement, but that requires a stored procedure rather than just a SQL statement.
正如您所说,使用原始 PreparedStatement 是不可能的。CallableStatement 是可能的,但这需要一个存储过程而不仅仅是一个 SQL 语句。
ORM layers like Hibernate also provide named parameter substitution, and Hibernate also allows you to execute native SQL, bypassing the OR mapping functionality completely.
像 Hibernate 这样的 ORM 层也提供命名参数替换,并且 Hibernate 还允许您执行本机 SQL,完全绕过 OR 映射功能。
So if you were really keen to use named parameters, you could employ Hibernate as a way of doing this; you'd only be using a tiny fraction of its functionality.
因此,如果您真的热衷于使用命名参数,您可以使用 Hibernate 作为这样做的一种方式;您只会使用其功能的一小部分。
回答by laz
Standard JDBC PreparedStatements don't have this ability. Spring JDBC provides this functionality through NamedParameterJdbcTemplate
.
标准的 JDBC PreparedStatements 没有这种能力。Spring JDBC 通过NamedParameterJdbcTemplate
.