使用JDBC准备语句使用变量而不是参数索引(Using a variable instead of a parameter index with a JDBC prepared statement)

编程入门 行业动态 更新时间:2024-10-23 17:27:32
使用JDBC准备语句使用变量而不是参数索引(Using a variable instead of a parameter index with a JDBC prepared statement)

在许多编程语言中,对于准备好的语句来说,这是可能的:

PreparedStatement statement = connection.prepareStatement( "SELECT id FROM Company WHERE name LIKE ${name}"); statement.setString("name", "IBM");

但不适用于java.sql.PreparedStatement。 在Java中,必须使用参数索引:

PreparedStatement statement = connection.prepareStatement( "SELECT id FROM Company WHERE name LIKE ?"); statement.setString(1, "IBM");

有没有像第一个例子一样使用字符串变量的解决方案? “$ {。*}”不是在SQL语言的其他地方使用,还是存在冲突? 因此,我会自己实现它(解析SQL字符串并将每个变量替换为“?”,然后以Java方式执行)。

问候,凯

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:

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).

Regards, Kai

最满意答案

标准JDBC PreparedStatements不具备此功能。 Spring JDBC通过NamedParameterJdbcTemplate提供了这个功能。

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

更多推荐

本文发布于:2023-08-07 20:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465994.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   语句   而不是   索引   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!