4

当我使用 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() 上执行 try/except 时出现以下异常:

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)

这个错误是怎么回事?

4

2 回答 2

2

发生异常时,您始终可以打印出错误:

try:
    transaction.commit()
except Exception, e:
    session.rollback()
    print str(e)
于 2011-04-10T13:40:34.460 回答
-2

搜索 Sqlalchemy 文档以启用 generatef d SQL 语句和 Sql 响应的日志记录。这通常会为您提供所有相关信息以供进一步调试。

于 2011-04-10T08:16:33.500 回答