概述
sqlalchemy 连接数据库
创建engine
from sqlalchemy import create_engine
engine = create_engine('sqlite:///xxx.db')
创建表结构
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
class MenuItem(Base):
__tablename__ = 'menu_item'
name =Column(String(80), nullable = False)
id = Column(Integer, primary_key = True)
description = Column(String(250))
price = Column(String(8))
course = Column(String(250))
restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
restaurant = relationship(Restaurant)
#We added this serialize function to be able to send JSON objects in a serializable format
@property
def serialize(self):
return {
'name' : self.name,
'description' : self.description,
'id' : self.id,
'price' : self.price,
'course' : self.course,
}
#创建表
Base.metadata.create_all(engine)
查询
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
#
egine = create_engine('sqlite:///restaurantmenu.db')
# 创建 session
Base.metadata.bind = engine
db_session = sessionmaker(bind=engin)
sess = db_session()
restaurant = Restaurant(name = "Pizza Palace")
sess.add(restaurant)
sess.commit()
# select
sess.query(Restaurant).all() # return a list
sess.query(Restaurant).first() # return an object
sess.query(Restaurant).filter_by(name='some_name') # return a list
sess.query(Restaurant).filter_by(name='some_name').one() # return an object
更新
rest = sess.query(Restaurant).filter_by(name='some_name').one()
rest.name = 'c'
sess.add(rest)
sess.commit() # 更新成功
删除
rest = sess.query(Restaurant).filter_by(name='some_name').one()
sess.delete(rest)
sess.commit()
CRUD Review
Operations with SQLAlchemy
In this lesson, we performed all of our CRUD operations with SQLAlchemy on an SQLite database. Before we perform any operations, we must first import the necessary libraries, connect to our restaurantMenu.db, and create a session to interface with the database:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantMenu.db')
Base.metadata.bind=engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
CREATE
We created a new Restaurant and called it Pizza Palace:
myFirstRestaurant = Restaurant(name = "Pizza Palace")
session.add(myFirstRestaurant)
sesssion.commit()
We created a cheese pizza menu item and added it to the Pizza Palace Menu:
cheesepizza = menuItem(name="Cheese Pizza", description = "Made with all natural ingredients and fresh mozzarella", course="Entree", price="$8.99", restaurant=myFirstRestaurant)
session.add(cheesepizza)
session.commit()
READ
We read out information in our database using the query method in SQLAlchemy:
firstResult = session.query(Restaurant).first()
firstResult.name
items = session.query(MenuItem).all()
for item in items:
print item.name
UPDATE
In order to update and existing entry in our database, we must execute the following commands:
Find Entry
Reset value(s)
Add to session
Execute session.commit()
We found the veggie burger that belonged to the Urban Burger restaurant by executing the following query:
veggieBurgers = session.query(MenuItem).filter_by(name= 'Veggie Burger')
for veggieBurger in veggieBurgers:
print veggieBurger.id
print veggieBurger.price
print veggieBurger.restaurant.name
print "n"
Then we updated the price of the veggie burger to $2.99:
UrbanVeggieBurger = session.query(MenuItem).filter_by(id=8).one()
UrbanVeggieBurger.price = '$2.99'
session.add(UrbanVeggieBurger)
session.commit()
DELETE
To delete an item from our database we must follow the following steps:
Find the entry
Session.delete(Entry)
Session.commit()
We deleted spinach Ice Cream from our Menu Items database with the following operations:
spinach = session.query(MenuItem).filter_by(name = 'Spinach Ice Cream').one()
session.delete(spinach)
session.commit()
最后
以上就是自信万宝路为你收集整理的sqlalchemy 操作数据库CRUDsqlalchemy 连接数据库的全部内容,希望文章能够帮你解决sqlalchemy 操作数据库CRUDsqlalchemy 连接数据库所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复