Skip to main content
 首页 » 编程设计

python之sqlalchemy 连接失败但 cx_oracle 成功

2025年05月04日16lexus

我正在尝试连接到 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)