Orm
The MySQL table structure is a two-dimensional table, which is represented by a Python data structure as a list, and each record is a tuple. As shown below:
[(' 1 ', ' Huangyi '), (' 2 ', ' Letian '), (' 3 ', ' Xiaosi ')]
This line is not easy to see the structure of the table, you can change it into the form of objects.
class User(object): def __init__(self, id, name): self.id = id self.name = name
Get:
[ User(‘1‘, ‘huangyi‘),User(‘2‘, ‘letian‘),User(‘3‘, ‘xiaosi‘)]
This is the ORM (Object-relational Mapping), which maps the table structure of the relational database to the object. We can use the SQLAlchemy framework to map.
SQLAlchemy
#!/usr/bin/env python#-*-coding:utf-8 -*-from sqlalchemy import Column, String, create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()class User(Base): __tablename__ = ‘user‘ id = Column(String(20), primary_key=True) name = Column(String(20))engine = create_engine(‘mysql+mysqlconnector://root:[email protected]: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.namesession.close()
Map the MySQL table structure to a Python object