sqlalchemy fails to connect but cx_oracle succeeds

会有一股神秘感。 提交于 2019-12-22 01:08:22

问题


I'm attempting to connect to an oracle server in Python. I have this working in cx_Oracle, but when I try to connect using sqlalchemy it fails. The cx_Oracle code:

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)

Executes and returns data from the database based on the query as expected. If I try the same connection with sqlalchemy:

import sqlalchemy

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

I get an error on the last line:

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)

Any idea what the problem is? Isn't sqlalchemy just using cx_Oracle? Is there any workaround to just give the cx_Oracle connection to sqlalchemy?


回答1:


Per the doc, the format of your Oracle connection string with SQLAlchemy should be oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]. But based on your former connection string, the db value might actually be the TNS service name, so in this case, you want to use

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


来源:https://stackoverflow.com/questions/48951981/sqlalchemy-fails-to-connect-but-cx-oracle-succeeds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!