作了最基本的操作,找找感觉。。

#coding=utf-8

from datetime import datetime
from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String, Boolean,
                        DateTime, ForeignKey, create_engine, CheckConstraint)
from sqlalchemy import (insert, select, update, delete, text, desc, cast, and_, or_, not_)
from sqlalchemy import (Table, ForeignKeyConstraint)
from sqlalchemy.sql import func
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (relationship, backref, sessionmaker)

Base = declarative_base()

class Cookie(Base):
    __tablename__ = 'cookies'

    cookie_id = Column(Integer(), primary_key=True)
    cookie_name = Column(String(50), index=True)
    cookie_recipe_url = Column(String(255))
    cookie_sku = Column(String(55))
    quantity = Column(Integer())
    unit_cost = Column(Numeric(12, 2))

    def __repr__(self):
        return "Cookie(cookie_name='{self.cookie_name}', " \
               "cookie_recipe_url='{self.cookie_recipe_url}', " \
               "cookie_sku='{self.cookie_sku}', " \
               "quantity={self.quantity}, " \
               "unit_cost={self.unit_cost})".format(self=self)

class User(Base):
    __tablename__ = 'users'

    user_id = Column(Integer(), primary_key=True)
    username = Column(String(15), nullable=False, unique=True)
    email_address = Column(String(255), nullable=False)
    phone = Column(String(20), nullable=False)
    password = Column(String(25), nullable=False)
    created_on = Column(DateTime(), default=datetime.now)
    updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.now)

    def __repr__(self):
        return "User(username='{self.username}', " \
               "email_address='{self.email_address}', " \
               "phone='{self.phone}', " \
               "password='{self.password}')".format(self=self)

class Order(Base):
    __tablename__ = 'orders'

    order_id = Column(Integer(), primary_key=True)
    user_id = Column(Integer(), ForeignKey('users.user_id'))
    shipped = Column(Boolean(), default=False)

    user = relationship("User", backref=backref('orders', order_by=order_id))

    def __repr__(self):
        return "Order(user_id={self.user_id}, " \
               "shipped={self.shipped})".format(self=self)

class LineItem(Base):
    __tablename__ = 'line_items'

    line_item_id = Column(Integer(), primary_key=True)
    order_id = Column(Integer(), ForeignKey('orders.order_id'))
    cookie_id = Column(Integer(), ForeignKey('cookies.cookie_id'))
    quantity = Column(Integer())
    extended_cost = Column(Numeric(12, 2))

    order = relationship("Order", backref=backref('line_items', order_by=line_item_id))
    cookie = relationship("Cookie", uselist=False)

    def __repr__(self):
        return "LineItems(order_id={self.order_id}, " \
               "cookie_id={self.cookie_id}, " \
               "quantity={self.quantity}, " \
               "extended_cost={self.extended_cost})".format(self=self)

engine = create_engine('mysql+pymysql://connection_str/cookies')
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()
'''
cc_cookie = Cookie(cookie_name='chocolate chip',
                   cookie_recipe_url='http://www.baidu.com/',
                   cookie_sku='CC01',
                   quantity=12,
                   unit_cost=0.50)
session.add(cc_cookie)
session.commit()

print(cc_cookie.cookie_id)

dcc = Cookie(cookie_name='dark chocolate chip',
             cookie_recipe_url='http://some.aweso.me/cookie/recipe_dark.html',
             cookie_sku='CC02',
             quantity=1,
             unit_cost=0.75)
mol = Cookie(cookie_name='molasses',
             cookie_recipe_url='http://some.aweso.me/cookie/recipe_molasses.html',
             cookie_sku='MOL01',
             quantity=1,
             unit_cost=0.80)
session.add(dcc)
session.add(mol)
session.flush()
print(dcc.cookie_id)
print(mol.cookie_id)

c1 = Cookie(cookie_name='peanut butter',
            cookie_recipe_url='http://some.aweso.me/cookie/peanut.html',
            cookie_sku='PB01',
            quantity=24,
            unit_cost=0.25)
c2 = Cookie(cookie_name='oatmeal raisin',
            cookie_recipe_url='http://some.okay.me/cookie/raisin.html',
            cookie_sku='EWW01',
            quantity=100,
            unit_cost=1.00)
session.bulk_save_objects([c1, c2])
session.commit()
print(c1.cookie_id)
'''
cookies = session.query(Cookie).all()
print(cookies)

for cookie in session.query(Cookie):
    print(cookie)

  

SQLAlchemy ORM之建表与查询的更多相关文章

  1. 64、django之模型层(model)--建表、查询、删除基础

    要说一个项目最重要的部分是什么那铁定数据了,也就是数据库,这篇就开始带大家走进django关于模型层model的使用,model主要就是操纵数据库不使用sql语句的情况下完成数据库的增删改查.本篇仅带 ...

  2. django之模型层(model)--建表、查询、删除基础

    要说一个项目最重要的部分是什么那铁定数据了,也就是数据库,这篇就开始带大家走进django关于模型层model的使用,model主要就是操纵数据库不使用sql语句的情况下完成数据库的增删改查.本篇仅带 ...

  3. 一次作业过程及其问题的记录:mysql建立数据库、建表、查询和插入等

    前言 这次的作业需要我建立一个小的数据库. 这次作业我使用了mysql,进行了建库.建表.查询.插入等操作. 以下是对本次作业相关的mysql操作过程及过程中出现的问题的记录. 正文 作业中对数据库的 ...

  4. sqlalchemy操作----建表 插入 查询 删除

    ... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import ...

  5. 第三次 orm自动建表及遇到的问题

    Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步. 方法很简单,在hibernate.cfg.xml内加入 <property name="hi ...

  6. sql 建表以及查询---复杂查询之成绩排名

    废话不说,直接建表 1.表Player USE T4st -- 设置当前数据库为T4st,以便访问sysobjects IF EXISTS(SELECT * FROM sysobjects WHERE ...

  7. Django ORM --- 建表、查询、删除基础

    1.什么是ORM ORM的全称是Object Relational Mapping,即对象关系映射.它的实现思想就是将关系数据库中表的数据映射成为对象,以对象的形式展现,这样开发人员就可以把对数据库的 ...

  8. SQL 建表与查询 HTML计算时间差

    create database xue1 go --创建数据库 use xue1 go --引用数据库 create table xinxi ( code int, name ), xuehao ), ...

  9. MySQL - 建库、建表、查询

    本章通过演示如何使用mysql客户程序创造和使用一个简单的数据库,提供一个MySQL的入门教程.mysql(有时称为“终端监视器”或只是“监视”)是一个交互式程序,允许你连接一个MySQL服务器,运行 ...

随机推荐

  1. js之作用域和面向对象

    作用域 JavaScript以函数为作用域 函数的作用域在函数未被调用之前,已经创建 函数的作用域存在作用域链,并且也是在被调用之前创建 示例一 xo = "alex"; func ...

  2. django的信号

    Django中提供了“信号调度”,用于在框架执行操作时解耦.通俗来讲,就是一些动作发生的时候,信号允许特定的发送者去提醒一些接受者. 1.Django内置信号 Model signals pre_in ...

  3. peewee 字段属性help_text的支持问题

    至少在__version__ = '2.6.0'的时候,给字段添加help_text的时候,在数据库的ddl语句里面是没有comment的. 看了下源码,顺藤摸瓜,最终定位到了字段(Field类)的_ ...

  4. Sort Transformed Array

    Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f( ...

  5. POJ 3903

    http://poj.org/problem?id=3903 这个题目是一个求最长递增子序列,这个只是求长度而已,所以可以用LIS 所谓的LIS也就是用二分优化来减少时间而已,而且其只能求出最长的序列 ...

  6. struts2 结果页面配置

    <result>标签: * 属性: * name:逻辑视图的名称 * type:结果页面类型. * dispatcher         :转发.默认值. * redirect       ...

  7. android气泡消息提醒布局

    无论是anroid还是ios,气泡消息提醒再正常不过了.然而要定义一个气泡消息提醒确要费一番周折.下面记录下气泡提醒布局. 定义气泡背景shape_unread_message_bg.xml < ...

  8. the XMLHttpRequest Object

    Ajax的核心是XMLHttpRequest对象.XMLHttpRequest对象允许异步发送请求并且以文本的形式返回结果.发送什么样的请求(what),在服务器端怎样处理这个请求(how),返回什么 ...

  9. Linux下安装Scala

    Linux下安装Scala和Windows下安装类似,步骤如下: 首先访问下载链接:http://www.scala-lang.org/download/默认这里下载的是Windows版本,这时点击上 ...

  10. 50道java算法题(一)

    [程序1] 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 1.程序分析:   兔子的规律为数列1 ...