我想使用 Python 通过 SSH 使用 Oracle SQLplus 运行 SQL 语句。到目前为止,我有以下代码:
import subprocess
sql = """
SET TIME OFF
SET TIMING OFF
SET HEADING OFF
SET LINESIZE 1000
SET PAGESIZE 0
SET TRIMSPOOL ON
SET FEEDBACK OFF
select name || '__a' from v$database;
"""
sql = sql.replace("'","\'").replace("$","\$")
export_cmd = "export ORACLE_HOME=/u01/oracle/19/srv; export ORACLE_SID=db01; export LD_LIBRARY_PATH=${ORACLE_HOME}/lib"
ssh_command = f"""{export_cmd}; echo "{sql}" | $ORACLE_HOME/bin/sqlplus -S / as sysdba"""
host = "host1"
process = subprocess.Popen(["ssh", f"oracle@{host}", ssh_command], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print("Output:\n", stdout.decode())
print("Error:\n", stderr.decode())
它工作正常。但我根本不想碰 SQL 语句,因为它是在该行中完成的:
sql = sql.replace("'","\'").replace("$","\$")
除了创建一个单独的 SQL 脚本然后使用 SQLplus 运行它之外,还有其他方法可以做到这一点吗?
有一个解决方案(使用heredoc):
import subprocess
sql = """SET TIME OFF
SET TIMING OFF
SET HEADING OFF
SET LINESIZE 1000
SET PAGESIZE 0
SET TRIMSPOOL ON
SET FEEDBACK OFF
select name || '__a' from v$database;
"""
export_cmd = "export ORACLE_HOME=/u01/oracle/19/srv; export ORACLE_SID=db01; export LD_LIBRARY_PATH=${ORACLE_HOME}/lib"
sqlplus = "${ORACLE_HOME}/bin/sqlplus"
ssh_command = f"""{export_cmd}; {sqlplus} -S / as sysdba <<'EOF'
{sql}
EOF
"""
host = "host1"
process = subprocess.Popen(["ssh", f"oracle@{host}", ssh_command], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print("Output:\n", stdout.decode())
print("Error:\n", stderr.decode())