使用 SQLAlchemy 从表中删除记录
Posted
技术标签:
【中文标题】使用 SQLAlchemy 从表中删除记录【英文标题】:deleting records from table using SQLAlchemy 【发布时间】:2017-02-13 11:30:02 【问题描述】:我想从测试表中删除一些数据。但即使在关注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_'
【问题讨论】:
非常相关:***.com/questions/9882358/… @IljaEverilä 我试过这个解决方案,但没有用。它返回:sqlalchemy.exc.UnboundExecutionError: This None is not directly bound to a Connection or Engine.Use the .execute() Connection 或 Engine 的方法来执行此构造。 【参考方案1】:Solution found on this post
我不得不使用:
d = t_packages.delete(t_packages.c.environment == 'sandbox')
with engine.connect() as conn:
conn.execute(d)
【讨论】:
以上是关于使用 SQLAlchemy 从表中删除记录的主要内容,如果未能解决你的问题,请参考以下文章