如何在cx_oracle上执行.sql文件?

时间:2019-01-30 05:55:04

标签: python oracle cx-oracle

我想使用cx_Oracle执行.sql文件。我必须执行许多文件,并且语句可能包含也可能不包含“;”终止之前。我已经通过以下解决方案了

f = open('tabledefinition.sql')
full_sql = f.read()
sql_commands = full_sql.split(';')

for sql_command in sql_commands:
    curs.execute(sql_command)

但这不起作用。 有没有办法像我那样为连接传递文件作为参数,如下所示:

dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)

like sql_file ='mysql.sql'吗?

1 个答案:

答案 0 :(得分:1)

您可以按原样使用模块运行 SQL:

from subprocess import Popen, PIPE

那么:

sqlrun = Popen(['sqlplus', 'User/Pass@DBINSTANCE'], shell=False , stdin=PIPE, stdout=PIPE, stderr=PIPE , encoding='utf8')

sqlrun.stdin.write('@' + 'tabledefinition.sql')

stdout, stderr = sqlrun.communicate()

退货状态:sqlrun.returncode
输出字符串:stdoutstderr

这用于 Unix shell 执行。

相关问题