时间:2021-07-01 10:21:17 帮助过:34人阅读
得到:
[ User(‘1‘, ‘huangyi‘), User(‘2‘, ‘letian‘), User(‘3‘, ‘xiaosi‘) ]
这就是ORM(Object-relational Mapping),把关系数据库的表结构映射到对象上。我们可以用SQLAlchemy框架来进行映射。
SQLAlchemy
#!/usr/bin/env python #-*-coding:utf-8 -*- from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = ‘user‘ id = Column(String(20), primary_key=True) name = Column(String(20)) engine = create_engine(‘mysql+mysqlconnector://root:XXXXX@localhost:3306/TUZHI‘) DBSession = sessionmaker(bind=engine) session = DBSession() new_user = User(id=‘4‘, name=‘Huangyi‘) session.add(new_user) session.commit() #session.close() ##进行查询 #session = DBSession() user = session.query(User).filter(User.id==‘4‘).one() print ‘type:‘, type(user) print ‘name:‘, user.name session.close()
MySQL表结构映射为Python中的对象 python (SQLAlchemy)
标签:self print mit 维表 记录 ima 列表 __init__ commit