18870715400
V2EX  ›  Python

Python 登录 oracle 的问题

By 18870715400 at 2020 年 10 月 14 日 · 3062 次点击

请问一下大佬,python 的 cx_Oracle 登录 oracle 需要客户端, 那么如何通过 tnsname.ora 的方式来登录 oracle 数据库呢, 也就是数据库机器的 ip 和端口放在 tnsname.ora 中, 而不是通过这种cx_Oracle.connect(config.USERNAME, self.password, "{ip}:{port}/{db}".format(ip=config.IP, port=config.PORT, db=config.DB)) 来登录

7 条回复  •  2020-10-15 09:28:26 +08:00
iqxd
   1
iqxd  
   2020 年 10 月 14 日
tnsname.ora 本身是一个文本文件,打开就可以看到 Dbname,IP,port,然后再用 connect 方法连接就行了.
noahliaszn
   2
noahliaszn  
   2020 年 10 月 14 日
你说的是类似与 plsql 这种 利用 tnsnames.ora 登录? 其实不就是读取配置文件吗。你把参数写在一个配置文件里面 去读不就行了。
iqxd
   3
iqxd  
   2020 年 10 月 14 日
如果一定要用.ora 文件的话,可以这样试试

cx_Oracle.connect(USERNAME,password, open('path/tnsname.ora','r').read())
krixaar
   4
krixaar  
   2020 年 10 月 14 日
connect 的第三个参数本来就可以用 tnsnames.ora 啊,比如里面有个 TEST.DB ,那么第三个参数直接写'TEST.DB'就连上了。

文档:
https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#net-service-names-for-connection-strings
black11black
   5
black11black  
   2020 年 10 月 15 日
问个题外话,现在 py 有成熟的异步 oracle 框架了吗
18870715400
   6
18870715400  
OP
   2020 年 10 月 15 日
TNS = """(DESCRIPTION=
(FAILOVER=on)
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.157.22)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.157.21)(PORT=1521)))
(CONNECT_DATA=(SERVICE_NAME={SERVER_NAME})))"""

conn = cx_oracle.connect(username, password, TNS)
18870715400
   7
18870715400  
OP
   2020 年 10 月 15 日
@iqxd 所需要的 tnsnames.ora 内容 和 实际配置里面的内容有些不太一样
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 37ms · 3.9.8.5