在 JDBC 准备好的语句中使用变量而不是参数索引 [英] Using a variable instead of a parameter index with a JDBC prepared statement

查看:18
本文介绍了在 JDBC 准备好的语句中使用变量而不是参数索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多编程语言中,预处理语句是可能的:

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

问候,凯

推荐答案

正如 kd304 在我帖子的评论中提到的那样,如果您不想将另一个 3rd 方库(如 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆