用户定义的变量由参数设置

时间:2017-07-23 09:03:13

标签: java sql jdbc h2

SQL正在使用的是:

SET @person1_id = ?;
SET @person2_id = ?;
SET @safety_factor = ?;
SELECT *
FROM table
WHERE person1 = @person1_id
AND person2 = @person2_id
AND safety_factor = @safety_factor;

这不是确切的代码,但显示了我正在尝试做的事情

我输入参数的方式是

Statement stmt = connection.prepareStatement(*script*)
stmt.setLong(1, person1.id)
stmt.setLong(2, person2.id)
stmt.setBigDecimal(3, safetyFactor)

我在sql中使用变量,因为在整个脚本中重复使用这些值,并且我不希望必须多次输入相同的值作为不同的参数。

这给了我一个错误,

  

线程“main”org.h2.jdbc.JdbcSQLException中的异常:值无效   “2”表示参数“parameterIndex”[90008-195]

我想这与脚本被视为四个单独的语句有关,但我不知道如何单独执行它们并让变量在语句之间起作用。

2 个答案:

答案 0 :(得分:1)

H2无法使用多个sql语句处理参数化查询。设置参数时,它只会看到第一个分号,这意味着它只能看到要设置的1个参数。

由于用户定义的变量是session scoped,我们可以在单独的语句中设置变量。

PreparedStatement statement = connection.prepareStatement("SET @person1_id = ?")
statement.setLong(1, person1.id)
statement.execute()

PreparedStatement statement = connection.prepareStatement("SET @person2_id = ?")
statement.setLong(1, person2.id)
statement.execute()
...

答案 1 :(得分:0)

我不知道这会有所帮助,但在这种情况下我通常使用另一种语法(对于SQL Server):

declare @person1_id long
declare @person2_id long
declare @safety_factor int

SELECT @person1_id=?, @person2_id=?, @safety_factor=?

SELECT *
FROM table
WHERE person1 = @person1_id
AND person2 = @person2_id
AND safety_factor = @safety_factor;
相关问题