Home > Backend Development > Python Tutorial > 把MySQL表结构映射为Python中的对象的教程

把MySQL表结构映射为Python中的对象的教程

WBOY
Release: 2016-06-10 15:16:08
Original
1330 people have browsed it

ORM

mysql的表结构是二维表,用python的数据结构表示出来就是一个列表,每一个记录是一个tuple。如下所示:

[('1', ''huangyi),('2', ''letian),('3', 'xiaosi')]

这一行并不便于看出表的结构,可以把它换成对象的形式。

class User(object):
  def __init__(self, id, name):
    self.id = id
    self.name = name
Copy after login

得到:

[ 
User('1', 'huangyi'),
 
User('2', 'letian'),
 
User('3', 'xiaosi')
]
Copy after login

这就是ORM(Object-relational Mapping),把关系数据库的表结构映射到对象上。我们可以用SQLAlchemy框架来进行映射。
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 = 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()
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template