python - 通过 python 运行整个 SQL 脚本

标签 python python-2.7

我希望运行位于 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/

相关文章:

python - 如何在正在运行的 Python 线程上调用函数

python - Django 模型和 View

python - Django allauth 电子邮件确认仅发送 html 代码

python - 使用 BeautifulSoup 导航到第二个字符串文本

Python有效地创建密度图

python - 如果脚本停止工作但仍显示在主管下运行,如何重新启动脚本

python - 堆叠 MultiIndex DataFrame 和合并索引

python selenium - 元素当前不可交互,可能无法操作

python - 将网络摄像头数据流式传输到网页

python - 限制每个 App Engine 实例的任务请求数