SQLAlchemy:update&从数据库中删除值

时间:2016-04-15 12:20:48

标签: python python-2.7 sqlite sqlalchemy

我是SQLAlchemy中的新手我使用一些示例来创建表并向其插入信息,并且它正在100%工作。

但我没有找到的是一些例子,我怎样才能更新&从数据库中删除一些信息。

我正在做的是:

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()

## create
class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

engine = create_engine('sqlite:///database.db')
Base.metadata.create_all(engine)

## insert

Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)

session = DBSession()
new_person = Person(name='new person')
session.add(new_person)
session.commit()

## fetch
getperson = session.query(Person).first()
print getperson.name

# this will print : new person

# I need some example to how can I update and delete this : new person

所以在这段代码中它会打印“新人”我的问题是如何更新或删除它?

1 个答案:

答案 0 :(得分:0)

以下是sqlalchemy中每个CRUD操作的一些示例(省略Create,Read,因为您已经知道如何执行这些操作): 首先,任何操作的必要进口和配置:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Category, Item, User are my tables
from database_setup import Base, Category, Item, User

# Generating session to connect to the db's ORM
engine = create_engine('sqlite:///catalogwithusers.db') # my db
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()

然后执行更新:

# Get the item filtering by it's id using a one() query on Item table
# If query is not empty, update the attributes, add query to session and commit

q = session.query(Item).filter_by(id=item_id).one()
if q != []:
    q.name = edited_name
    q.description = edited_description
    session.add(q)
    session.commit()

最后,执行删除:

# Again get the item similarly to the example above
# Then if query returned results, use the delete method and commit
q = session.query(Item).filter_by(id=item_id).one()
if q != []:
    session.delete(q)
    session.commit()

这些示例来自here。我建议你看看。 ORM Creation在database_setup.py中,CRUD操作在project.py和populatecatalog.py中执行。