python - sqlalchemy 连接失败但 cx_oracle 成功

标签 python sqlalchemy cx-oracle

我正在尝试连接到 Python 中的 oracle 服务器。我在 cx_Oracle 中有这个工作,但是当我尝试使用 sqlalchemy 连接时它失败了。 cx_Oracle 代码:

import cx_Oracle
import pandas as pd

cx_connection = cx_Oracle.connect(user+'/' + pw + '@' + host + ':' + port + '/' + db)
df = pd.read_sql(my_query, cx_connection)

根据预期的查询执行并从数据库返回数据。如果我尝试与 sqlalchemy 进行相同的连接:

import sqlalchemy

engine = sqlalchemy.create_engine('oracle+cx_oracle://' + user + ':' + pw + '@' + host + ':' + port + '/' + db)
sqlalchemy_connection = engine.connect()

最后一行出现错误:

DatabaseError: (cx_Oracle.DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (Background on this error at: http://sqlalche.me/e/4xp6)

知道问题出在哪里吗? sqlalchemy 不就是用cx_Oracle 吗?是否有任何解决方法可以将 cx_Oracle 连接提供给 sqlalchemy?

最佳答案

根据 doc ,你的 Oracle 连接字符串与 SQLAlchemy 的格式应该是 oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]。但是根据您以前的连接字符串,db 值实际上可能是 TNS 服务名称,因此在这种情况下,您要使用

engine = sqlalchemy.create_engine('oracle+cx_oracle://' + user + ':' + pw + '@' + host + ':' + port + '/?service_name=' + db)

关于python - sqlalchemy 连接失败但 cx_oracle 成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951981/

相关文章:

python - Python 中的 cx_Oracle、生成器和线程

Python - 链表 - 追加

python - 我怎样才能得到下图的黑白图像?

python - 在 python C API 中创建模块时如何包含 __build_class__

python - Matplotlib 导航工具栏 : remove "Edit curves lines and axes parameters"

python - 为什么带有 charset=utf8 的 SQLAlchemy create_engine 返回 python 类型 <str> 而不是类型 <unicode>?

python - Oracle WHERE 子查询中的多个列 "cx_Oracle.DatabaseError: ORA-00920: invalid relational operator"

Python、SQLAlchemy 在 connection.execute 中传递参数

Python MySQL 连接器返回 bytearray 而不是常规字符串值

django - 如何在 CentOS 6 上导入 cx_Oracle?