我遇到了一个令人讨厌的小问题,使用服务名称通过 SQLAlchemy 连接到 Oracle 模式。这是我作为脚本的代码。(出于安全原因,尖括号之间的项目是实际值的占位符)
from sqlalchemy import create_engine
if __name__ == "__main__":
engine = create_engine("oracle+cx_oracle://<username>:<password>@<host>/devdb")
result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)")
result = engine.execute("drop table test_table")
其中“devdb”是服务名称而不是 SID。运行此脚本的结果是堆栈跟踪。
(oracle-test)[1]jgoodell@jgoodell-MBP:python$ python example.py
Traceback (most recent call last):
File "example.py", line 8, in <module>
result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)")
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1621, in execute
connection = self.contextual_connect(close_with_result=True)
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1669, in contextual_connect
self.pool.connect(),
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 272, in connect
return _ConnectionFairy(self).checkout()
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 425, in __init__
rec = self._connection_record = pool._do_get()
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 777, in _do_get
con = self._create_connection()
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 225, in _create_connection
return _ConnectionRecord(self)
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 318, in __init__
self.connection = self.__connect()
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 368, in __connect
connection = self.__pool._creator()
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 80, in connect
return dialect.connect(*cargs, **cparams)
File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/default.py", line 279, in connect
return self.dbapi.connect(*cargs, **cparams)
sqlalchemy.exc.DatabaseError: (DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor
None None
如果 'devdb' 是一个 SID 而不是一个服务名称,这个例子就可以正常工作,我一直在尝试连接字符串的不同排列,但没有找到任何有效的方法。SQLAlchemy 文档中似乎也没有任何内容明确解释如何处理 Oracle 连接的 SID 与服务名称。