本文摘自php中文网,作者零下一度,侵删。
SQLAlchemy是Python的ORM框架,它的理念是:数据库的量级和性能重要于对象集合,而对象集合的抽象又重要于表和行。数据库操作软件,类似于php里面的pdo,但是比pdo更灵活、复杂,能将数据库中的表和程序中的class一一对应,方便调用,如果前期能写好class,后期不用写sql;
安装
1 | pip install flask_sqlalchemy
|
创建表:
1 | 1 from flask_sqlalchemy import SQLAlchemy 2 from sqlalchemy import * 3 from sqlalchemy.orm import * 4 #上面导入的文件可能有些用不到; 5 engine=create_engine( "mysql://root:root@localhost:3306/flask?charset=utf8" , echo =True) 6 metadata=MetaData(engine) 7 goods=Table( 'goods' ,metadata, 8 Column( 'id' ,Integer,primary_key=True), 9 Column( 'name' ,String(20)),10 Column( 'fullname' ,String(40)),11 )12 metadata.create_all()
|
插入数据:
1 | 1 #-*-coding:utf-8-*- 2 from flask_sqlalchemy import SQLAlchemy 3 from sqlalchemy import * 4 from sqlalchemy.orm import * 5 #链接数据库并初始化对象 6 engine=create_engine( "mysql://root:root@localhost:3306/flask?charset=utf8" , echo =True) 7 metadata=MetaData(engine) 8 9 users_table = Table( "goods" ,metadata,autoload=True) #这个应该是初始化表10 i = users_table.insert() #调用对象中的insert()方法,产生语句:INSERT INTO goods (id, name, fullname) VALUES (%s, %s, %s)11 result = i.execute(name = "summer" ,fullname = "736960938@qq.com" ) #传入参数并执行12 print (result)
|
查询数据
1、看到插入数据用的这种方式,于是想到了查询应该也可以吧;
1 | 1 users_table = Table( "goods" ,metadata,autoload = True)2 i = users_table.select()3 result = i.execute(name= "xiaoge" )4 #这种方式查询好像有点尴尬,对象里面包含对象,不能直接看到查询结果5 print (result)
|
2、将表与class建立对应关系
1 | 1 goods_table = Table( "goods" ,metadata,autoload = True) 2 '' ' 3 建立表和class的映射关系 4 ' '' 5 class Goods(object): 6 def __repr__(self): 7 return "%s(%r,%r)" % (self. __class__ ,self.name,self.fullname) 8 mapper(Goods,goods_table) 9 '' '建立关系结束' '' 10 session = create_session()11 query = session.query(Goods)12 u=query.filter_by(name = "xiaoge" ).first()13 print (u.fullname)
|
object.__dict__查看对象中的内容,不递归显示
查询所有数据:
1 | 1 goods_table = Table( "goods" ,metadata,autoload = True) 2 '' ' 3 建立表和class的映射关系 4 ' '' 5 class Goods(object): 6 def __repr__(self): 7 return "%s(%r,%r)" % (self. __class__ ,self.name,self.fullname) 8 mapper(Goods,goods_table) 9 '' '建立关系结束' '' 10 session = create_session()11 query = session.query(Goods)12 u = query.all()13 for i in u:#返回多个对象,遍历即可14 print (i.name)
|
以上就是sqlalchemy的实例介绍的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
盘点Python中断多重循环的思路
Python是怎么计算auc指标的?
pycharm在创建py文件时,自动添加文件头注释的实例
Python如何将整数转化为字符串
Python 文件夹遍历和文件查找的实例
Python3.7怎么安装pip
Python中json序列化的详细分析
Python标准数据类型有哪些
Python能做什么游戏
Python是什么类型的编程语言?
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » sqlalchemy的实例介绍