简体   繁体   中英

How to execute .sql file on cx_oracle?

I want to execute a .sql file using cx_Oracle. I have to execute many files and the statements may or may not contain ';' before termination. I have gone though following solution

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

for sql_command in sql_commands:
    curs.execute(sql_command)

but this does not work. Is there any way to pass file as parameter like i do for connection as follows:

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' ?

You can run the SQL as is using the module:

from subprocess import Popen, PIPE

Then:

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()

return status: sqlrun.returncode
Output strings: stdout , stderr

This for Unix shell execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM