SQLAlchemy ORM之建表与查询
作了最基本的操作,找找感觉。。
#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之建表与查询的更多相关文章
- 64、django之模型层(model)--建表、查询、删除基础
要说一个项目最重要的部分是什么那铁定数据了,也就是数据库,这篇就开始带大家走进django关于模型层model的使用,model主要就是操纵数据库不使用sql语句的情况下完成数据库的增删改查.本篇仅带 ...
- django之模型层(model)--建表、查询、删除基础
要说一个项目最重要的部分是什么那铁定数据了,也就是数据库,这篇就开始带大家走进django关于模型层model的使用,model主要就是操纵数据库不使用sql语句的情况下完成数据库的增删改查.本篇仅带 ...
- 一次作业过程及其问题的记录:mysql建立数据库、建表、查询和插入等
前言 这次的作业需要我建立一个小的数据库. 这次作业我使用了mysql,进行了建库.建表.查询.插入等操作. 以下是对本次作业相关的mysql操作过程及过程中出现的问题的记录. 正文 作业中对数据库的 ...
- sqlalchemy操作----建表 插入 查询 删除
... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import ...
- 第三次 orm自动建表及遇到的问题
Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步. 方法很简单,在hibernate.cfg.xml内加入 <property name="hi ...
- sql 建表以及查询---复杂查询之成绩排名
废话不说,直接建表 1.表Player USE T4st -- 设置当前数据库为T4st,以便访问sysobjects IF EXISTS(SELECT * FROM sysobjects WHERE ...
- Django ORM --- 建表、查询、删除基础
1.什么是ORM ORM的全称是Object Relational Mapping,即对象关系映射.它的实现思想就是将关系数据库中表的数据映射成为对象,以对象的形式展现,这样开发人员就可以把对数据库的 ...
- SQL 建表与查询 HTML计算时间差
create database xue1 go --创建数据库 use xue1 go --引用数据库 create table xinxi ( code int, name ), xuehao ), ...
- MySQL - 建库、建表、查询
本章通过演示如何使用mysql客户程序创造和使用一个简单的数据库,提供一个MySQL的入门教程.mysql(有时称为“终端监视器”或只是“监视”)是一个交互式程序,允许你连接一个MySQL服务器,运行 ...
随机推荐
- linux操作系统flash player问题--ubuntu
adobe公司停止了对linux系统的flash player的更新,这导致很多网页视频不能够通过浏览器观看,很是不爽! 还好,给用户留下了一点点希望,那便是chrome浏览器. 谷歌浏览器,有一款插 ...
- 代码高亮插件SyntaxHighlighter
http://alexgorbatchev.com/SyntaxHighlighter/download/
- Extjs使用Ext.function.bind, 给句柄函数传参
回调函数updateImage中的key参数,在外部调用时有程序员自己指定. 使用Ext.Function.bind(this.updateImage, this, 'imageUrl', true) ...
- 【Nginx】nginx 代理 Haproxy 怎么设置?
由于Haproxy是通过 url 正则匹配 识别 的,nginx代理到 haproxy需要设置 proxy_set_header Host 为 haproxy的目标 url 直接上配置 upstrea ...
- Redis Sentinel机制与用法(一)
Sentinel spring 集群配置: 概述 Redis-Sentinel是Redis官方推荐的高可用性(HA)解决方案,当用Redis做Master-slave的高可用方案时,假如master宕 ...
- SQL Server 流程控制
流程控制语句: BEGIN ... END WAITFOR GOTO WHILE IF ... ELSE BREAK RETURN CONTINURE 1.BEGIN ... END BEGIN ...
- C++中string,wstring,CString的基本概念和用法
一.概念 string和CString均是字符串模板类,string为标准模板类(STL)定义的字符串类,已经纳入C++标准之中.wstring是操作宽字符串的类.C++标准程序库对于string的设 ...
- Linux下常用的硬件信息查看命令
1.查看CPU型号,这里为了方便查看结合管道符用grep进行了匹配,当然只需要前面的命令也可以,命令如下: cat /proc/cpuinfo | grep "model name" ...
- HDU 4870 Rating(概率、期望、推公式) && ZOJ 3415 Zhou Yu
其实zoj 3415不是应该叫Yu Zhou吗...碰到ZOJ 3415之后用了第二个参考网址的方法去求通项,然后这次碰到4870不会搞.参考了chanme的,然后重新把周瑜跟排名都反复推导(不是推倒 ...
- BestCoder19 1001.Alexandra and Prime Numbers(hdu 5108) 解题报告
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5108 题目意思:给出一个数正整数 N,N <= 1e9,现在需要找出一个最少的正整数 M,使得 ...