当我使用SQLAlchemy插入MySQL时,我看到消息“ROLLBACK”出现在开发服务器的输出日志中。我怎么知道回滚发生的原因?
2011-04-10 00:35:32,736 INFO [sqlalchemy.engine.base.Engine.0x...4710][MainThread] INSERT INTO pageview (time, unit_id, visitor_id, url_id, referrer_id, reservation_id, visit_id) VALUES (%s, %s, %s, %s, %s, %s, %s)
2011-04-10 00:35:32,736 INFO [sqlalchemy.engine.base.Engine.0x...4710][MainThread] (datetime.datetime(2011, 1, 31, 0, 1, 53), 120L, 5538L, 11075L, 11076L, 5538L, None)
2011-04-10 00:35:32,737 INFO [sqlalchemy.engine.base.Engine.0x...4710][MainThread] ROLLBACK
Starting server in PID 10158.
serving on 0.0.0.0:6543 view at http://127.0.0.1:6543
我注意到在每个外键值之后出现字母“L”(例如:unit_id字段是“120L”而不是“120”)。这可能与这个问题有关吗?
这是执行插入的python代码:
@classmethod
def unconverted(class_):
session = DBSession()
return session.query(class_).filter(class_.pageview == None).order_by(class_.time).limit(5).all()
@classmethod
def convert_all(class_):
session = DBSession()
unconverted = class_.unconverted()
for item in unconverted:
pageview = PageView(raw_request=item)
item.pageview = pageview
session.add(item)
session.flush()
transaction.commit()
session.close()
编辑:
根据plaes的建议,在session.flush()上尝试/除外,我得到以下异常:
2011-04-10 11:33:44,462 INFO [sqlalchemy.engine.base.Engine.0x...3750][MainThread] ROLLBACK
(IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`metrics`.`pageview`, CONSTRAINT `pageview_ibfk_1` FOREIGN KEY (`unit_id`) REFERENCES `unit` (`id`))') 'INSERT INTO pageview (time, unit_id, visitor_id, url_id, referrer_id, reservation_id, visit_id) VALUES (%s, %s, %s, %s, %s, %s, %s)' (datetime.datetime(2011, 1, 31, 0, 1, 53), 120L, 5608L, 11215L, 11216L, 5608L, None)
发生了什么错误?
答案 0 :(得分:2)
发生异常时,您始终可以打印错误:
try:
transaction.commit()
except Exception, e:
session.rollback()
print str(e)
答案 1 :(得分:1)
搜索Sqlalchemy文档以启用generatef的日志记录 d SQL语句和Sql响应。这通常会为您提供进一步调试的所有相关信息。