2012-11-26 158 views
0

我有下面的代码.sql文件:我可以使用SQLPlus执行.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 
/

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

回答

6

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

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

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

+0

所以脚本运行正常,但.sql没有做它应该做的事情。如果我打开SQLPLUS并在程序中运行该文件,它会正确地填充oracle表,但是使用该脚本不会填充表。任何想法为什么发生这种情况?运行脚本时是否需要打开SQLPLUS? – Steve83

+0

我最终需要做到这一点,以至于我为它创建了一个超级基础类:https://github.com/danie665/tools/blob/master/sql_plus.py – mut3

1

下面是如何做到这一点的一个例子。您需要读取文件并将整个字符串作为命令传递。

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

conn_string = " %s/%[email protected]%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() 
相关问题