插入多行并返回主键时,我注意到一些奇怪的事情。如果我在isert查询中添加使用参数值,我会得到预期的行为,但是当将值传递给游标时,不会返回任何内容。
这可能是一个错误,还是我误解了什么?
我的sqlachemy版本是0.9.4,低于如何重现错误:
from sqlalchemy import create_engine, Column, Unicode, DateTime
from sqlalchemy import Float, ForeignKey, BigInteger, Enum, Integer, Boolean
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
cmd= 'postgresql+psycopg2://lfiaschi:mypswd@localhost:5432/test_db'
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
db_id = Column(BigInteger, primary_key=True, autoincrement=True)
name = Column(Unicode(255), nullable=False)
engine=create_engine(cmd, encoding='utf8', implicit_returning=False)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
N=10
rows = [{'name': str(i)} for i in range(N)]
#If the values are specified at this point the primary keys seem correctly returned
ins_statement1 = Test.__table__.insert(returning=[Test.__table__.c.db_id]).values(rows)
connection = engine.connect()
res1 = connection.execute(ins_statement1)
correct_ids = res1.fetchall()
print correct_ids
assert len(correct_ids) == N
ins_statement1 = Test.__table__.insert(returning=[Test.__table__.c.db_id])
#If we specify the values here
res2 = connection.execute(ins_statement1,rows)
res2.fetchall() #BOOOM!
我得到的错误是:
File "bug_sqlalchemy.py", line 42, in <module>
res2.fetchall() #BOOOM!
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 788, in fetchall
self.cursor, self.context)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1108, in _handle_dbapi_exception
exc_info
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 185, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 782, in fetchall
l = self.process_rows(self._fetchall_impl())
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 749, in _fetchall_impl
return self.cursor.fetchall()
sqlalchemy.exc.ProgrammingError: (ProgrammingError) no results to fetch None None
有人能解释一下这个区别吗?
重新插入插入行的主键的最合适方法是什么?