sqlalchemy整理(四)

 接之前的一二三

三中是建立类,获取table信息,然后将两者绑定,达到面向对象

1.通过类来建立数据库,真的面向对象

2.依旧利用configparse读取配置文件

3.通过session add delete update 等

import ConfigParser

#get the connect db conf 
def read_conf(db_type="mysql"):
    conf=ConfigParser.ConfigParser()
    conf.read("./db.conf")
    sec=db_type
    db_user=conf.get(sec,"db_user")
    db_password=conf.get(sec,"db_password")
    db_host=conf.get(sec,"db_host")
    db_port=conf.get(sec,"db_port")
    db_name=conf.get(sec,"db_name")
    return "{0}://{1}:{2}@{3}:{4}/{5}".format(db_type,db_user,db_password,db_host,db_port,db_name)

#class test two#############################################
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, mapper, relation, sessionmaker


#get db url
db_url=read_conf()
print db_url
Base=declarative_base()
class Coder(Base):
    __tablename__="coder"
    id=Column(Integer,primary_key=True)
    name=Column(String(10),default="hello")
    lang=Column(String(10),default="PHP,Python,Go")
    
    def __init__(self,name,lang):
        self.id=id
        self.name=name
        self.lang=lang
    def __repr__(self):
        return "<Codere('%s','%s', '%s')>" % (self.id, self.name, self.lang)

engine = create_engine(db_url, echo=True)
metadata=Base.metadata
metadata.create_all(bind=engine,checkfirst=True)

Session=sessionmaker(bind=engine)
session=Session()

coder=Coder("xluren","PHP,Python,Go")
session.add(coder)
session.flush()
session.commit()

coders=session.query(Coder)
for coder in coders:
    print coder.id,coder.name,coder.lang
    session.delete(coder)

coders=session.query(Coder)
for coder in coders:
    print coder.id,coder.name,coder.lang


你可能感兴趣的:(sqlalchemy整理(四))