How would you connect to an Oracle database on a on premise server remotelly using Python? I've tried with the library cx_Oracle but I can't figure out how to connect to a database that's not on my local computer nor the cloud
import oracledb
import traceback
import os
un = os.environ.get('PYTHON_USERNAME')
pw = os.environ.get('PYTHON_PASSWORD')
cs = os.environ.get('PYTHON_CONNECTSTRING')
try:
connection = oracledb.connect(user=un, password=pw, dsn=cs)
with connection.cursor() as cursor:
sql = """select systimestamp from dual"""
for r in cursor.execute(sql):
print(r)
except oracledb.Error as e:
error, = e.args
traceback.print_tb(e.__traceback__)
print(error.message)
1条答案
按热度按时间azpvetkf1#
假设网络和防火墙允许连接,那么我将执行以下操作:
然后使用如下脚本:
关键是要将
PYTHON_CONNECTSTRING
环境变量设置为什么。从“Easy Connect”语法开始。找到运行数据库的主机名或IP地址(例如myhost.oracle.com)。找到服务名称(不是数据库的旧“SID”)(例如,服务名称可能是'orclpdb1')。还会有一个正在监听的端口(默认值为1521)。然后将PYTHON_CONNECTSTRING
环境变量设置为myhost.oracle.com:1521/orclpdb1
。还有其他可用的连接字符串语法,如手册中所示。