简体   繁体   中英

sqlalchemy fails to connect but cx_oracle succeeds

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM