向NativeQuery添加多个参数时出现无效字符异常

时间:2015-04-29 16:20:06

标签: sql jdbc

我使用JDBC并希望创建一个包含两个参数的NativeQuery,其中一个是String,另一个是int。当我尝试这样做时:

import javax.persistence.EntityManager;
...
private final EntityManager entityManager;
....
String columnName = "exampleName";
int columnNumber = 5;
entityManager.createNativeQuery("SELECT c.TABLE_NAME, c.TCL_NUMBER from COL_NAME c where c.TABLE_NAME " +
                    "like ?1 and c.TCL_NUMBER like ?2;")
                .setParameter(1, columnName)
                .setParameter(2, columnNumber)
                .getSingleResult();

我收到java.sql.SQLSyntaxErrorException: ORA-00911: invalid character例外。 这是我的SQL:

CREATE TABLE COL_NAME (
  TABLE_NAME               VARCHAR2(50 BYTE),
  TABLE_NUMBER             NUMBER(10,0)
);

当我想将int设置为参数时,是否必须考虑一些特殊内容?

1 个答案:

答案 0 :(得分:0)

正如您已经发现查询中的问题来自?1?2。这将被编译为:

SELECT c.TABLE_NAME, c.TCL_NUMBER from COL_NAME c where c.TABLE_NAME like 'val1'1 and c.TCL_NUMBER like 'val2'2 

这显然是不正确的sql语法。

所以正确的代码是:

entityManager.createNativeQuery("SELECT c.TABLE_NAME, c.TCL_NUMBER from COL_NAME c where c.TABLE_NAME " +
                "like ? and c.TCL_NUMBER = ? ")
            .setParameter(1, columnName)
            .setParameter(2, columnNumber)
            .getSingleResult();