简体   繁体   English

使用变量而不是参数索引和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");

But not with java.sql.PreparedStatement. 但不是java.sql.PreparedStatement。 In Java one has to use parameter indices: 在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? “$ {。*}”是否未在SQL语言中的其他位置使用,或者是否存在冲突? 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字符串并用“?”替换每个变量,然后用Java方式)。

Regards, Kai 问候,凯

Standard JDBC PreparedStatements don't have this ability. 标准JDBC PreparedStatements没有此功能。 Spring JDBC provides this functionality through NamedParameterJdbcTemplate . Spring JDBC通过NamedParameterJdbcTemplate提供此功能。

正如我在帖子评论中提到的kd304,如果您不想将另一个第三方库(如Spring)合并到您的项目中,这是一个非常好的解决方案: Javaworld文章:PreparedStatement的命名参数

Using a raw PreparedStatement, this is not possible, as you say. 正如你所说,使用原始的PreparedStatement是不可能的。 It is possible with CallableStatement, but that requires a stored procedure rather than just a SQL statement. 可以使用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; 因此,如果你真的热衷于使用命名参数,你可以使用Hibernate作为这样做的一种方式; you'd only be using a tiny fraction of its functionality. 你只使用它的一小部分功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM