Home > Article > Backend Development > Example introduction of sqlalchemy
SQLAlchemy is Python's ORM framework. Its philosophy is that the size and performance of the database are more important than the object collection, and the abstraction of the object collection is more important than the tables and rows.
Database operation software is similar to pdo in php, but more flexible and complex than pdo. It can match the tables in the database to the classes in the program one-to-one, making it easy to call. If you can write the class well in the early stage, No need to write sql later;
pip install flask_sqlalchemy
Create table:
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()
Insert data:
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 users_table = Table("goods",metadata,autoload = True)2 i = users_table.select()3 result = i.execute(name="xiaoge")4 #这种方式查询好像有点尴尬,对象里面包含对象,不能直接看到查询结果5 print(result)
2. Establish a corresponding relationship between the table and 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)
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)
The above is the detailed content of Example introduction of sqlalchemy. For more information, please follow other related articles on the PHP Chinese website!