使用sqlalchemy的OverflowError

时间:2015-01-29 01:19:53

标签: python postgresql sqlalchemy

使用SQLAlchemy连接到数据库时遇到问题。我已经使用这个包很长时间来连接到我们拥有的所有数据库。最近尝试连接到新数据库并收到以下错误:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@host/db')
engine.connect()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1778, in connect
    return self._connection_cls(self, **kwargs)
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 60, in __init__
    self.__connection = connection or engine.raw_connection()
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1847, in raw_connection
    return self.pool.unique_connection()
  File "C:\Python27\lib\site-packages\sqlalchemy\pool.py", line 280, in unique_connection
    return _ConnectionFairy._checkout(self)
  File "C:\Python27\lib\site-packages\sqlalchemy\pool.py", line 644, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Python27\lib\site-packages\sqlalchemy\pool.py", line 440, in checkout
    rec = pool._do_get()
  File "C:\Python27\lib\site-packages\sqlalchemy\pool.py", line 963, in _do_get
    return self._create_connection()
  File "C:\Python27\lib\site-packages\sqlalchemy\pool.py", line 285, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Python27\lib\site-packages\sqlalchemy\pool.py", line 416, in __init__
    exec_once(self.connection, self)
  File "C:\Python27\lib\site-packages\sqlalchemy\event\attr.py", line 250, in exec_once
    self(*args, **kw)
  File "C:\Python27\lib\site-packages\sqlalchemy\event\attr.py", line 260, in __call__
    fn(*args, **kw)
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\strategies.py", line 157, in on_connect
    do_on_connect(conn)
  File "C:\Python27\lib\site-packages\sqlalchemy\dialects\postgresql\psycopg2.py", line 530, in on_connect
    for fn in fns:
OverflowError: Python int too large to convert to C long

奇怪的是,对于某些数据库,我的连接完全正常,但是对于这个特定的数据库,我得到了OverflowError。有关为什么会发生这种情况的任何想法?我们正在使用postgresql

1 个答案:

答案 0 :(得分:1)

问题是由psycopg2中的hstore实现引起的。在连接时,psycopg2尝试使用获取hstore OID的本机hstore实现。这些OID超出C长范围值,因此会抛出错误。

您可以通过在create_engine

中传递use_native_hstore = False来解决此问题
engine = create_engine('postgresql://username:password@host/db', use_native_hstore=False)