使用SQLAlchemy从表中删除记录

时间:2017-02-13 11:30:03

标签: python sqlalchemy

我想从测试表中删除一些数据。但即使在this documentation之后,我也不确定我做错了什么。:

hostname = 'localhost'
db_name = 'xx'
db_port = 'xx'
login = 'xx'
pwd = 'xx'

con_string = 'mysql+mysqlconnector://{login}:{passwd}@{hostname}:{port}/{db}'
engine_str = con_string.format(
    login=login, passwd=pwd, hostname=hostname, port=db_port, db=db_name
)

try:
    engine = sqlalchemy.create_engine(engine_str, echo=False)
    session = sessionmaker(bind=engine)
    connection = engine.connect()
    session = session(bind=connection)
    Base = declarative_base()

except exc.SQLAlchemyError:
    raise


t_packages = Table('test_table', Base.metadata, autoload_with=engine)
session.query(t_packages).filter_by(environment='sandbox').delete()

错误消息:

 line 119, in delete_package_reference_by_env
    session.query(t_packages).filter_by(environment=environment).delete()
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 3155, in delete
    delete_op.exec_()
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\persistence.py", line 1167, in exec_
    self._do_pre_synchronize()
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\persistence.py", line 1221, in _do_pre_synchronize
    target_cls = query._mapper_zero().class_
AttributeError: 'NoneType' object has no attribute 'class_'

1 个答案:

答案 0 :(得分:0)

Solution found on this post

我不得不使用:

d = t_packages.delete(t_packages.c.environment == 'sandbox')
with engine.connect() as conn:
    conn.execute(d)