python - 在 python 中使用 cx_Oracle 使用 PL/SQL 和 DML/DDL 解析 SQL 文件

标签 python oracle cx-oracle

我有一个 SQL 文件,我想使用 cx_Oracle python 库在 oracle 中解析和执行它。 SQL 文件包含经典的 DML/DDL 和 PL/SQL,例如。它看起来像这样:

创建.sql:

-- This is some ; malicious comment
CREATE TABLE FOO(id numeric);

BEGIN
  INSERT INTO FOO VALUES(1);
  INSERT INTO FOO VALUES(2);
  INSERT INTO FOO VALUES(3);
END;
/
CREATE TABLE BAR(id numeric);

如果我在 SQLDeveloper 或 SQL*Plus 中使用这个文件,它将被分成 3 个查询并执行。

但是,cx_Oracle.connect(...).cursor().execute(...) 一次只能接受一个查询,而不是整个文件。我不能简单地使用 string.split(';') 拆分字符串(如此处建议的 execute a sql script file from cx_oracle? ),因为注释将被拆分(并且会导致错误)和 PL/SQL block 将不会作为单个命令执行,从而导致错误。

在 Oracle 论坛 ( https://forums.oracle.com/forums/thread.jspa?threadID=841025 ) 上,我发现 cx_Oracle 本身不支持解析整个文件这样的事情。我的问题是——有没有工具可以帮我做这件事?例如。我可以调用一个 python 库来将我的文件拆分成查询?

编辑:最好的解决方案似乎是直接使用 SQL*Plus。我用过这段代码:

# open the file
f = open(file_path, 'r')
data = f.read()
f.close()

# add EXIT at the end so that SQL*Plus ends (there is no --no-interactive :(
data = "%s\n\nEXIT" % data

# write result to a temp file (required, SQL*Plus takes a file name argument)
f = open('tmp.file', 'w')
f.write(data)
f.close()

# execute SQL*Plus
output = subprocess.check_output(['sqlplus', '%s/%s@%s' % (db_user, db_password, db_address), '@', 'tmp.file'])

# if an error was found in the result, raise an Exception
if output.find('ERROR at line') != -1:
    raise Exception('%s\n\nStack:%s' % ('ERROR found in SQLPlus result', output))

最佳答案

同时执行多个语句是可能的,但它是半 hacky。您需要包装您的语句并一次执行它们。

>>> import cx_Oracle
>>>
>>> a = cx_Oracle.connect('schema/pw@db')
>>> curs = a.cursor()
>>> SQL = (("""create table tmp_test ( a date )"""),
... ("""insert into tmp_test values ( sysdate )""")
... )
>>> for i in SQL:
...     print i
...
create table tmp_test ( a date )
insert into tmp_test values ( sysdate )
>>> for i in SQL:
...     curs.execute(i)
...
>>> a.commit()
>>>

正如您所注意到的,这并不能解决分号问题,因为分号问题没有简单的答案。在我看来,您有 3 个选择:

  1. 写一个过于复杂的解析器,我认为这根本不是一个好的选择。

  2. 不要从 Python 执行 SQL 脚本;将代码放在单独的 SQL 脚本中以便解析很容易,在单独的 Python 文件中,嵌入到 Python 代码中,在数据库中的过程中......等等。这可能是我的首选。

    <
  3. 使用 subprocess 并以这种方式调用脚本。这是最简单、最快捷的选项,但根本不使用 cx_Oracle

    >>> import subprocess
    >>> cmdline = ['sqlplus','schema/pw@db','@','tmp_test.sql']
    >>> subprocess.call(cmdline)
    
    SQL*Plus: Release 9.2.0.1.0 - Production on Fri Apr 13 09:40:41 2012
    
    Copyright (c) 1982, 2002, Oracle Corporation.  All rights reserved.
    
    
    Connected to:
    Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
    
    SQL>
    SQL> CREATE TABLE FOO(id number);
    
    Table created.
    
    SQL>
    SQL> BEGIN
      2    INSERT INTO FOO VALUES(1);
      3    INSERT INTO FOO VALUES(2);
      4    INSERT INTO FOO VALUES(3);
      5  END;
      6  /
    
    PL/SQL procedure successfully completed.
    
    SQL> CREATE TABLE BAR(id number);
    
    Table created.
    
    SQL>
    SQL> quit
    Disconnected from Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
    0
    >>>
    

关于python - 在 python 中使用 cx_Oracle 使用 PL/SQL 和 DML/DDL 解析 SQL 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10137495/

相关文章:

Python - 将标题写入 csv

python - 谷歌 Bigquery 存储 : DeadlineExceeded Error when reading to_dataframe

python - scikit-学习 PCA : matrix transformation produces PC estimates with flipped signs

python - XGBRegressor 评分方法返回奇怪的值

python - 我的错误 : List or tuple literal expected as the second argument to namedtuple()

sql - 将 R Dataframe 中的多行插入 Oracle 数据库

sql - 使用 ROWNUM 时的区别

sql - 在 Oracle 中,如何对多个数组使用 IN 子句?

python - 如何使用 python 和 cx_Oracle 更新 oracle 表中的列并在每次记录更新后提交

python - 数据库错误 : ORA-00911: invalid character