2012-11-26 213 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() 
相關問題