Python - sqlalchemy - oracle connection fails to connect to SID

為{幸葍}努か 提交于 2020-04-30 05:45:54

问题


I am trying to use sqlalchemy to connect to an oracle DB. I was expecting the following to work given that it appears the exact syntax is shown in the sqlalchemy documentation.

oracle_db = sqlalchemy.create_engine('oracle://user:pass@server:1521/dev')

but this results in the error:

dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs) TypeError: makedsn() takes no keyword arguments

The following call initially works without the service name

oracle_db = sqlalchemy.create_engine('oracle://user:pass@server:1521')

But when trying to connect it fails with an error complaining that the SERVICE_NAME was not provided.

ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Oddly this works with cx_Oracle directly:

con = cx_Oracle.connect('user/pass@server:1521/dev')

How am I supposed to connect to the specific service?

Attempts

I have tried to use cx_Oracle.makedsn() explicitly from this question with no luck as well.

Trying to use ? options in the connection string

oracle_db = sqlalchemy.create_engine('oracle://user:pass@server:1521/?sid=dev')

works initially but when I try oracle_db.connect() I get the same ORA-12504 error shown above.


回答1:


Based on the documentation at Sqlalchemy Documentation, you should probably use the cx_oracle engine. The connect string is:

oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]

with an option of service_name or sid as follows:

oracle+cx_oracle://user:pass@host:1521/?service_name=hr
oracle+cx_oracle://user:pass@host:1521/?sid=hr



回答2:


Try using this connection string:

engine = create_engine("oracle+cx_oracle://<username>:<password>@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = <host>)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = devdb)))") 

It worked for me.



来源:https://stackoverflow.com/questions/36455358/python-sqlalchemy-oracle-connection-fails-to-connect-to-sid

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