oracle 我可以使用 SQLPlus 执行 .sql 文件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13568014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 01:17:20  来源:igfitidea点击:

Can I use SQLPlus to execute a .sql file?

pythonoraclesqlplus

提问by Steve83

I have a .sql file with the following code:

我有一个包含以下代码的 .sql 文件:

delete from stalist
where stalistid=4944
/
insert into stalist
(stalistid, staid)
(select distinct 4944, staid
from staref
Where staid in(
3797,3798,
3870,4459,
3871,3872,
3876,3877,
0
))
/
commit
/

I would like to use Python to execute this file from SQLPlus. Is this possible? I do not have any python experience in this type of work and could use some help. Thank you!

我想使用 Python 从 SQLPlus 执行此文件。这可能吗?我在此类工作中没有任何 Python 经验,可以使用一些帮助。谢谢!

回答by DazzaL

see this tutorial: http://moizmuhammad.wordpress.com/2012/01/31/run-oracle-commands-from-python-via-sql-plus/

请参阅本教程:http: //moizmuhammad.wordpress.com/2012/01/31/run-oracle-commands-from-python-via-sql-plus/

i.e.

IE

from subprocess import Popen, PIPE

#function that takes the sqlCommand and connectString and retuns the output and #error string (if any)

def runSqlQuery(sqlCommand, connectString):

session = Popen(['sqlplus', '-S', connectString], stdin=PIPE, stdout=PIPE, stderr=PIPE)
session.stdin.write(sqlCommand)
return session.communicate()

should do it (where sqlCmmand is "@scriptname.sql").

应该这样做(其中 sqlCmmand 是“@scriptname.sql”)。

回答by Neerav

Below is an example of how to do this. You need to read the file and pass the entire string as a command.

下面是如何执行此操作的示例。您需要读取文件并将整个字符串作为命令传递。

(username, password, host) = ("user","password","host") 

conn_string = " %s/%s@%s "% (username,password,host)
session = Popen(['sqlplus','-S', conn_string], stdin=PIPE, stdout=PIPE, stderr=PIPE)
logging.info("Starting sqlplus")

sql_file = '%s/%s' % (sql_folder, file)
logging.info("Running " + sql_file)
f= open(sql_file,'r')
cmd = f.read()
session.stdin.write(cmd)

stdout, stderr = session.communicate()