Orm
MySQL's table structure is a two-dimensional table, expressed in Python data structure is a list, 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 ORM (Object-relational Mapping), which maps the table structure of relational databases to objects. We can use the SQLAlchemy framework for mapping.
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 = Declarati Ve_base () class User (base): __tablename__ = ' User ' id = column (string (), primary_key=true) name = Column ( ) 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. Cl OSE () # #进行查询 #session = dbsession () user = Session.query (user). Filter (user.id== ' 4 '). One () print ' type: ', type (user) Prin T ' name: ', User.Name session.close ()