该代码是 sqlahcmey 的orm 教程的分步复制,除了最后一行,我打算在查询后删除所有表。但是程序被阻塞了Base.metadata.drop_all(bind=engine)
,下面是MySQL当时的状态(取自MySQL Workbench):
如标记行所示,drop table 进程由于 被挂起
table metadata lock
,我认为元数据锁定是由于result = session.query(User).all()
如果删除该行,程序没有阻塞,但我仍然不知道原因。所以我的问题是:为什么会发生这种情况,如何避免阻塞
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(16))
fullname = Column(String(16))
password = Column(String(16))
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
def __repr__(self):
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
uri = 'mysql://root:zxsaqw21@localhost/test_sa'
engine = create_engine(uri, echo=False)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
user = User('ed', 'Ed Jones', 'edspassword')
session.add(user)
session.commit()
result = session.query(User).all()
print len(result)
Base.metadata.drop_all(bind=engine)