简体   繁体   English

通过Oracle的JDBC驱动程序解析SQL

[英]Parse SQL via Oracle's JDBC driver

I'd like to test whether given SQL statement is syntactically and semantically valid (ie. no syntax errors and no field misspellings). 我想测试给定的SQL语句在语法和语义上是否有效(即没有语法错误,没有字段拼写错误)。

For most databases Connection.prepareStatement and PreparedStatement.getMetaData would do the trick (no exception == good query). 对于大多数数据库, Connection.prepareStatementPreparedStatement.getMetaData都可以实现这一目的(无异常==良好查询)。 Unfortunately Oracle's newest driver only parses like this only SELECT queries, but not other kind of queries. 不幸的是,Oracle最新的驱动程序只解析这样的SELECT查询,而不是其他类型的查询。 Older drivers don't do even that. 年长的司机甚至不这样做。

Is there some other facility provided by Oracle for parsing SQL statements? Oracle是否提供了一些其他工具来解析SQL语句?

You can use the Oracle DBMS_SQL package to parse a statement held in a string. 您可以使用Oracle DBMS_SQL包来解析字符串中保存的语句。 For example: 例如:

SQL> declare
  2    c integer;
  3    l_statement varchar2(4000) := 'insert into mytable (col) values (1,2)';
  4  begin
  5    c := dbms_sql.open_cursor;
  6    dbms_sql.parse(c,l_statement,dbms_sql.native);
  7    dbms_sql.close_cursor(c);
  8  end;
  9  /
declare
*
ERROR at line 1:
ORA-00913: too many values
ORA-06512: at "SYS.DBMS_SYS_SQL", line 824
ORA-06512: at "SYS.DBMS_SQL", line 32
ORA-06512: at line 6

You could wrap that up into a stored function that just returned eg 1 if the statement was valid, 0 if invalid, like this: 您可以将其包装到刚刚返回的存储函数中,例如,如果语句有效则返回1,如果无效则返回0,如下所示:

function sql_is_valid
  ( p_statement varchar2
  ) return integer
is  
  c integer;
begin
  c := dbms_sql.open_cursor;
  dbms_sql.parse(c,p_statement,dbms_sql.native);
  dbms_sql.close_cursor(c);
  return 1;
exception
  when others then 
    return 0;
end;

You could then use it something like this PL/SQL example: 然后你可以使用像这个PL / SQL例子:

:n := sql_is_valid('insert into mytable (col) values (1,2)');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM