ORM
mysql的表结构是二维表,用python的数据结构表示出来就是一个列表,每一个记录是一个tuple。如下所示:
[('1', ''huangyi),('2', ''letian),('3', 'xiaosi')]
这一行并不便于看出表的结构,可以把它换成对象的形式。
1
2
3
4
|
class User( object ): def __init__( self , id , name): self . id = id self .name = name |
得到:
1
2
3
4
5
6
7
|
[ User( '1' , 'huangyi' ), User( '2' , 'letian' ), User( '3' , 'xiaosi' ) ] |
这就是ORM(Object-relational Mapping),把关系数据库的表结构映射到对象上。我们可以用SQLAlchemy框架来进行映射。
SQLAlchemy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#!/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() |