首頁  >  文章  >  後端開發  >  sqlalchemy的實例介紹

sqlalchemy的實例介紹

零下一度
零下一度原創
2017-07-17 14:01:391470瀏覽

SQLAlchemy是Python的ORM框架,它的理念是:資料庫的量級和效能重要於物件集合,而物件集合的抽象又重要於表格和行。

資料庫操作軟體,類似php裡面的pdo,但是比pdo更靈活、複雜,能將資料庫中的表和程式中的class一一對應,方便調用,如果前期能寫好class,後期不用寫sql;

 
安裝
pip install flask_sqlalchemy

#建立表格:

 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 #-*-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 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 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 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的實例介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn