【问题标题】:Oracle: ORA-00911: invalid characterOracle: ORA-00911: 无效字符
【发布时间】:2017-06-10 22:05:28
【问题描述】:

在我的代码中,我有以下查询字符串:

   private static final String QUERY = format(
                    "  SELECT t2.address " +
                    "  FROM schema.table1 t1    ," +
                    "  schema.table2 t2 ," +
                    "  schema.table3 t3            ,"+
                    "  schema.table4 t4 " +
                    "  WHERE t2.uniqueIdentifier =:%s " +
                    "  AND  t1.parent_id = t2.parent_alias " +
                    "  AND t3.company_id  = t1.company_id " +
                    "  AND t3.record_age  = t2.recordAge " +
                    "  AND t2.name = 'stubName' " +
                    "  AND t4.pln_foi_id = t2.recordAge ",uniqueIdentifier);

在原生查询中调用如下:

 public String getAddress(String uniqueIdentifier){

        String result = null;

        try {
            Query query = persistence.entityManager().createNativeQuery(QUERY);
            query.setParameter("uniqueIdentifier", uniqueIdentifier);
            result = query.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

当我测试这个查询时,我得到以下信息:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Caused by: java.sql.SQLSyntaxErrorException: ORA-00911: invalid character

什么可能导致此错误?我在我的查询字符串或代码中看不到任何可能导致它的问题。

【问题讨论】:

  • t2.uniqueIdentifier =:%s 这是不正确的。
  • 请对此进行扩展或给出答案
  • 变量 uniqueIdentifier 中应该包含哪些值?可能是导致问题
  • 它必须是 t2.uniqueIdentifier = ? 之类的东西
  • 您的格式结果返回一个以SELECT t2.address , FROM 开头的字符串,在我看来, 不应该存在。

标签: java string oracle hibernate nativequery


【解决方案1】:

查询应该是

...
"  WHERE t2.uniqueIdentifier = :uniqueIdentifier "
...

并删除对String.format()的调用;根据第一个 uniqueIdentifier 变量的值,您将受到 SQL 注入或 setParameter() 无法工作。

说明:当您有一个带参数的本机查询时,您需要在查询中使用:(冒号)前缀指定参数的名称。要使用参数foo,请将:foo 放入查询中并调用setParameter("foo", value); 以指定应使用哪个值代替参数。

【讨论】:

  • 我已经尝试过了,我得到了同样的错误。我认为查询语法一定有其他问题
  • 您可以记录查询和参数并尝试在 SQL 工具中手动运行吗?它们通常可以突出显示语法错误。如果失败,请尝试调试代码并查看 SQLException 内部。它将包含查询中违规字符的偏移量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2011-04-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多