简体   繁体   中英

Connexion to oracle server with SQLAlchemy and cx_Oracle

Today i come to you because i would like to connect my oracle localhost server to my script. So i've the following code:

import sqlalchemy
import cx_Oracle

connexion_string=str('oracle+cx_oracle://' + con['sql']['user'] + ':' + con['sql']['password'] + '@' + con['sql']['server'] + ':' + con['sql']['port'] + '/?service_name=' + con['sql']['database'])

try:
   engine = sqlalchemy.create_engine(connexion_string)
   conn = engine.connect()
except Exception as e:
   print(type(e))

With this code, I have the following error:

<class 'sqlalchemy.exc.DatabaseError'>

I don't have any idea why it's not working, if someone could help me, it should be nice !

I'm working with SQLAlchemy 1.3.18 and cx_Oracle 8.0.0 with python 3.8.3 (it's also working on 3.7.6)

Have a nice day !

I use sqlalchemy and cx_oracle in this way:

from sqlalchemy import create_engine
import cx_Oracle

host="myhost"
port=myport
sid='myservicename'
user='myuser'
password='mypassword'
sid = cx_Oracle.makedsn(host, port, service_name=sid)

cstr = 'oracle://{user}:{password}@{sid}'.format(
    user=user,
    password=password,
    sid=sid
)

engine =  create_engine(
    cstr,
    convert_unicode=False,
    pool_recycle=10,
    pool_size=50,
    echo=True,
    max_identifier_length=128
)

result = engine.execute('select * from dual')

for row in result:
    print (row)

C:\python>python mytest_sql.py
2020-08-12 14:14:12,136 INFO sqlalchemy.engine.base.Engine SELECT USER FROM DUAL
2020-08-12 14:14:12,137 INFO sqlalchemy.engine.base.Engine {}
2020-08-12 14:14:12,192 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60 CHAR)) AS anon_1 FROM DUAL
2020-08-12 14:14:12,192 INFO sqlalchemy.engine.base.Engine {}
2020-08-12 14:14:12,247 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR2(60 CHAR)) AS anon_1 FROM DUAL
2020-08-12 14:14:12,248 INFO sqlalchemy.engine.base.Engine {}
2020-08-12 14:14:12,303 INFO sqlalchemy.engine.base.Engine SELECT CAST('test nvarchar2 returns' AS NVARCHAR2(60)) AS anon_1 FROM DUAL
2020-08-12 14:14:12,304 INFO sqlalchemy.engine.base.Engine {}
2020-08-12 14:14:12,383 INFO sqlalchemy.engine.base.Engine select value from nls_session_parameters where parameter = 'NLS_NUMERIC_CHARACTERS'
2020-08-12 14:14:12,383 INFO sqlalchemy.engine.base.Engine {}
2020-08-12 14:14:12,490 INFO sqlalchemy.engine.base.Engine select * from dual
2020-08-12 14:14:12,492 INFO sqlalchemy.engine.base.Engine {}
('X',)

C:\python>

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