使用变量而不是参数索引和JDBC预处理语句 [英] Using a variable instead of a parameter index with a JDBC prepared statement
问题描述
在许多编程语言中,预处理语句都可以这样:
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");
但不是java.sql.PreparedStatement。在Java中,必须使用参数索引:
But not with java.sql.PreparedStatement. In Java one has to use parameter indices:
PreparedStatement statement = connection.prepareStatement(
"SELECT id FROM Company WHERE name LIKE ?");
statement.setString(1, "IBM");
是否有解决方案可以使用第一个示例中的字符串变量?
$ {。*}是否在SQL语言的其他地方没有使用,或者是否有任何冲突?因为我会自己实现它(解析SQL字符串并用?替换每个变量然后用Java方式)。
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).
问候,
Kai
Regards, Kai
推荐答案
正如我发布的评论中提到的kd304,如果你不想这是一个非常好的解决方案将另一个第三方库(如Spring)合并到您的项目中: Javaworld文章:PreparedStatement的命名参数
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
这篇关于使用变量而不是参数索引和JDBC预处理语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!