码迷,mamicode.com
首页 > 数据库 > 详细

SQLAlchemy MySQL 基础

时间:2015-05-20 08:14:22      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

__author__ = Steve

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()


# define the schema of table
class Users2(Base):
    __tablename__ = users2
    name = Column(String(45), nullable=True)
    id = Column(Integer, primary_key=True)


# you can direct query database, but it is not recommended
def test_conn():
    username = root
    passwd = 123
    schema = test
    engine = create_engine(
        "mysql://{0}:{1}@127.0.0.1/{2}?charset=utf8&use_unicode=0".format(username, passwd, schema))
    result = engine.execute("select name from users2")
    for row in result:
        print "name:", row[name]
    result.close()


def conn():
    username = root
    passwd = 123
    schema = test
    engine = create_engine(
        "mysql+mysqldb://{0}:{1}@127.0.0.1/{2}?charset=utf8&use_unicode=0".format(username, passwd, schema))
    Base.metadata.bind = engine
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    return session


def query():
    session = conn()
    rows = session.query(Users2).all()
    for row in rows:
        print row.id, row.name


def insert():
    user = Users2(name="steve", id=3)
    session = conn()
    session.add(user)
    session.commit()


def delete():
    session = conn()
    user = session.query(Users2).filter_by(name=steve2).one()
    print "delete user:", user.name
    session.delete(user)
    session.commit()


def update():
    session = conn()
    user = session.query(Users2).filter_by(name=steve).one()
    user.name = steve2
    session.commit()


if __name__ == "__main__":
    query()
    print
    # insert()
    # delete()
    # update()
    query()

 

SQLAlchemy MySQL 基础

标签:

原文地址:http://www.cnblogs.com/phoenix13suns/p/4516227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!