5.5.使用更通用的sqlalchemy操作数据库
2017-10-07 本文已影响0人
郑司令
# 导入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
#sqlalchemy依赖于mysqldb,而mysqldb被改为pymysql
#因此要将pymysql声明为mysqldb
import pymysql
pymysql.install_as_MySQLdb()
# 创建对象的基类:
Base = declarative_base()
# 定义User对象:
class Angle2(Base):
# 表的名字:
__tablename__ = 'angle2'
# 表的结构:
id = Column(String(20), primary_key=True)
name = Column(String(20))
# 初始化数据库连接:
engine = create_engine('mysql://root:@localhost:3306/Angle', echo = True)
一、创建表:
Base.metadata.create_all(engine)
二、查看是否创建成果:
engine.table_names()
三、初始化一个session对象:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
通过session对象,可以对数据库进行操作。
四、添加、更新对象
user_1 = User(id=1, name='wang', password='123')
session.add(user_1)
user_2 = User(id=2, name='qian', password='234')
user_3 = User(id=3, name='sun', password='345')
session.add_all([user_2, user_3])
session.commit()
session.dirty:查看删除对象
session.dirty:查看新增对象
session.rollback():回滚
五、查询
session.query(User).filter_by(name='wang').first()
session.query(User).filter_by(name='wang').all()
for name in session.query(User.name).filter_by(password='123'):
print(name)
for user in session.query(User).order_by(User.id)[1:3]:
print(user.name)
六、查询时的通用过滤符号:
# equal
query.filter(User.name == 'ed')
# not equal
query.filter(User.name != 'ed')
# like
query.filter(User.name.like('%ed%'))
# in
query.filter(User.name.in_(['ed', 'wendy', 'jack']))
# not in
query.filter(~User.name.in_(['ed', 'wendy', 'jack']))
# add
# use and_()
from sqlalchemy import and_
query.filter(and_(User.name == 'ed', User.fullname == 'Ed Jones'))
# or send multiple expressions to .filter()
query.filter(User.name == 'ed', User.fullname == 'Ed Jones')
# or chain multiple filter()/filter_by() calls
query.filter(User.name == 'ed').filter(User.fullname == 'Ed Jones')
# or --Make sure you use or_() and not the Python or operator!
from sqlalchemy import or_
query.filter(or_(User.name == 'ed', User.name == 'wendy'))
# match
query.filter(User.name.match('wendy'))
参考链接:http://www.cnblogs.com/wswang/p/5826347.html
https://linux-wang.gitbooks.io/sqlalchemy-docs-cn/content/SQLAlchemyORM/Object-Relational-Tutorial.html