欢迎来到Doc100.Net免费学习资源知识分享平台!
您的位置:首页 > 程序异常 >

python学习课程(八)sqlalchemy的classic映射

更新时间: 2014-01-05 02:07:58 责任编辑: Author_N1

 

python学习教程(八)sqlalchemy的classic映射

首先,我们来创建一个配置文件,其中包含数据库中表的映射关系,文件名为:dbsetting.py

from sqlalchemy.orm import mapper
from sqlalchemy import Table, MetaData, Column, Integer, String, DateTime
from datetime import datetime
from sqlalchemy.engine import create_engine
'''the connection to the database'''
engine = create_engine("mysql://root:1933jld1945js@localhost/test",isolation_level="READ UNCOMMITTED") 
'''the construct of the database table'''
metadata = MetaData()
people = Table( #people
                'people', metadata,
                Column('id', Integer, primary_key=True),
                Column('name', String(16), unique=True, nullable=False),
                Column('gender', String(255), unique=True, nullable=True),
                Column('created', DateTime, default=datetime.now)
                )
student = Table( #student
                'student', metadata,
                Column('id', Integer, primary_key=True),
                Column('name', String(16), unique=True, nullable=False),
                Column('gender', String(255), unique=True, nullable=True),
                Column('created', DateTime, default=datetime.now)
                )
teacher = Table( #teacher
                'teacher', metadata,
                Column('id', Integer, primary_key=True),
                Column('name', String(16), unique=True, nullable=False),
                Column('gender', String(255), unique=True, nullable=True),
                Column('created', DateTime, default=datetime.now)
                )
'''create database class'''
class People(object):pass
class Student(object):pass
class Teacher(object):pass
'''classic'''
mapper(People,people)
mapper(Student,student)
mapper(Teacher,teacher)
'''create tables'''
metadata.create_all(engine)


然后,我们可以写一个文件,测试一下,文件代码如下:

from dbproject.dbsetting import People,Teacher,engine
from sqlalchemy.orm import sessionmaker

people = People()
teahcer = Teacher()
people.name='renlei'
people.id=1
teahcer.name='laoshi'
teahcer.id=1
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
session.add(people)
session.add(teahcer)
session.flush()
session.commit()


上一篇:上一篇
下一篇:下一篇

 

随机推荐程序问答结果

 

 

如对文章有任何疑问请提交到问题反馈,或者您对内容不满意,请您反馈给我们DOC100.NET论坛发贴求解。
DOC100.NET资源网,机器学习分类整理更新日期::2014-01-05 02:07:58
如需转载,请注明文章出处和来源网址:http://www.doc100.net/bugs/t/6005/
本文WWW.DOC100.NET DOC100.NET版权所有。