This article mainly introduces how to map the MySQL table structure to an object in Python and use the SQLAlchemy Library in Python. For more information, see
ORM
The mysql table structure is a two‑dimensional table, which is represented by the python data structure as a list. each record is a tuple. As follows:
[('1', ''huangyi), ('2', ''letian), ('3', 'xiaosi')]
This row is not easy to see the structure of the table. you can replace it with an object.
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 for ING.
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 (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 () # Query # session = DBSession () user = session. query (User ). filter (User. id = '4 '). one () print 'type: ', type (user) print 'name:', user. namesession. close ()