【问题标题】:Executing SQL files with multiple queries on Python 2.7 using cx_oracle使用 cx_oracle 在 Python 2.7 上执行带有多个查询的 SQL 文件
【发布时间】:2016-08-04 08:47:33
【问题描述】:

我在通过 cx_oracle 运行一些 .sql 文件时遇到了实际问题。例如,如果我通过 Oracle Developer 运行,下面的 test_table2.sql 可以完美运行。

declare
c int;
begin
select count(*) into c from user_tables where table_name = upper('TEST2');
if c = 1 then
  execute immediate 'drop table TEST2';
end if;

EXECUTE IMMEDIATE 'CREATE TABLE MURRAYLR.test2 as 
select * from Dans_Table';

EXECUTE IMMEDIATE'CREATE TABLE MURRAYLR.test1
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
)';

end;

Python 代码通常适用于简单查询,但一旦我尝试检查现有表脚本,它就会给我错误。见下文

Python 2.7.11 代码

import sys
import cx_Oracle

connection = cx_Oracle.connect('user','password','serv')
cursor = connection.cursor()

filename="C:\Users\desktop\Test_table2.sql"

f = open(filename)
full_sql = f.read()
sql_commands = full_sql.replace('\n', '').split(';')[:-1]

for sql_command in sql_commands:
cursor.execute(sql_command)

connection.close()

错误信息

cursor.execute(sql_command) 数据库错误:ORA-06550:第 1 行,第 15 列: PLS-00103:在预期以下情况之一时遇到符号“文件结尾”:

:= 。 ( @ % ; 非空范围默认字符

【问题讨论】:

    标签: python oracle python-2.7 cx-oracle


    【解决方案1】:

    我没有尝试运行您的代码(因为没有使用 cxOracle 安装 Python),但看起来您正在将匿名 PL/SQL 块拆分为多个单独的语句:

    sql_commands = full_sql.replace('\n', '').split(';')[:-1]
    

    因此,您尝试执行的第一个 SQL 命令是

    declare
      c int;
    

    这没有任何意义。由于您已经将所有命令放在一个匿名 PL/SQL 块中,因此您根本不需要拆分它 - 只需将整个块作为单个命令运行,就可以了。

    更新

    完整的解决方案(未经测试):

    import sys
    import cx_Oracle
    
    connection = cx_Oracle.connect('user','password','serv')
    cursor = connection.cursor()
    
    filename="C:\Users\desktop\Test_table2.sql"
    
    f = open(filename)
    full_sql = f.read()
    cursor.execute(full_sql)
    
    connection.close()
    

    【讨论】:

    • 弗兰克,我不确定我是否理解您的解决方案。你能帮我看看代码吗?
    • @LeeMurray 查看我的更新答案;我无法测试它,但它应该可以工作(可能稍作修改,我最近没有做太多 Python)
    • 说匿名块的末尾有一个/。在 / 之后,该表有一个授权语句,后面跟着另一个 /。我们如何处理这种稍微改变的情况?
    猜你喜欢
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2018-05-14
    • 2012-04-25
    • 2021-11-18
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多