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_base base = Declarative_base () class User (base): __ tablename__ = ' user ' id = column (string (), primary_key=true) name = column (string) 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.namesession.close ()