我希望运行位于 C:
驱动器上文件夹中的以下 test.sql
。我一直在使用 cx_Oracle,但无法让它工作。
test.sql
包含以下内容。
CREATE TABLE MURRAYLR.test
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
CREATE TABLE MURRAYLR.test2
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
这是我的代码:
import sys
import cx_Oracle
connection = cx_Oracle.connect('user,'password,'test.ora')
cursor = connection.cursor()
f = open("C:\Users\desktop\Test_table.sql")
full_sql = f.read()
sql_commands = full_sql.split(';')
for sql_command in sql_commands:
cursor.execute(sql_command)
cursor.close()
connection.close()
最佳答案
仅当您的 test.sql 文件包含新行 '\n\' 字符时,此答案才相关(就像我从复制粘贴您的 sql 代码中获得的那样)。您需要在代码中删除它们(如果存在)。要检查,请执行
print full_sql
要修复“\n”,
sql_commands = full_sql.replace('\n', '').split(';')[:-1]
以上内容应该有所帮助。
在分割 sql 字符串时,它会删除 '\n' 并删除末尾的空字符串标记。
关于python - 通过 python 运行整个 SQL 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36574621/