【问题标题】:Can I use SQLPlus to execute a .sql file?我可以使用 SQLPlus 执行 .sql 文件吗?
【发布时间】:2012-11-26 15:33:31
【问题描述】:

我有一个包含以下代码的 .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 经验,可以使用一些帮助。谢谢!

【问题讨论】:

    标签: python oracle sqlplus


    【解决方案1】:

    请参阅本教程: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”)。

    【讨论】:

    • 所以脚本运行正确,但是 .sql 没有做它应该做的事情。如果我打开 SQLPLUS 并在程序中运行该文件,它会正确填充 oracle 表,但使用脚本不会填充该表。知道为什么会这样吗?运行脚本时需要打开 SQLPLUS 吗?
    • 我打开了文件 f= open('mysql.sql','rb') cmd = f.read() 它运行成功但是没有从sqlfile执行ddl
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      相关资源
      最近更新 更多