如何使用Python远程连接到内部部署服务器上的Oracle数据库

roejwanj  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(194)

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

azpvetkf

azpvetkf1#

假设网络和防火墙允许连接,那么我将执行以下操作:

python -m pip install oracledb

然后使用如下脚本:

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)

关键是要将PYTHON_CONNECTSTRING环境变量设置为什么。从“Easy Connect”语法开始。找到运行数据库的主机名或IP地址(例如myhost.oracle.com)。找到服务名称(不是数据库的旧“SID”)(例如,服务名称可能是'orclpdb1')。还会有一个正在监听的端口(默认值为1521)。然后将PYTHON_CONNECTSTRING环境变量设置为myhost.oracle.com:1521/orclpdb1
还有其他可用的连接字符串语法,如手册中所示。

相关问题