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服务器,运行 ...
随机推荐
- 4-python学习——数据操作
4-python学习--数据操作 参考python类型转换.数值操作(收藏) Python基本运算符 数据类型转换: 有时候,可能需要执行的内置类型之间的转换.类型之间的转换,只需使用类名作为函数. ...
- MongoDB 查询优化分析
摘要: 在MySQL中,慢查询日志是经常作为我们优化查询的依据,那在MongoDB中是否有类似的功能呢?答案是肯定的,那就是开启Profiling功能.该工具在运行的实例上收集有关MongoDB的写操 ...
- 7.SpringMVC注解优化
新建controller,每个人都可以建自己的controller,比较方便,不用再在web.xml中进行配置,value的请求地址一定要唯一. 优化: 1.上面示例中spring-annotatio ...
- Python—>Mysql—>Dbvisualizer
MySQLdb: https://pypi.python.org/pypi/MySQL-python/1.2.4 import MySQLdb 1.Download Connector/Python: ...
- js注册读秒进度条
转载自://http://blog.csdn.net/wugouzi/article/details/12621385 <head> <meta http-equiv="C ...
- C++基础练习题(一): 查找最短单词
/*<说明> 编程实现将字符串中最短的单词输出,在主函数中输入字符串,编写一个函数完成最短单词的查找 </说明>*/ #include<time.h> #inclu ...
- Jquery 点击按钮将其背景图换成另一张,再次点击恢复默认图片
这是Jquery代码: $(function () { $("#h1").toggle(function () { $("#h1").css("bac ...
- MVC3.0删除数据的时候给提示信息
Index.cshtml代码: @model IEnumerable<FirstMvc.Models.Book> <script type="text/javascript ...
- 模拟操作网页 webBrowser
C# 获取IFrame中body元素 (winform) 方法1. 找出iframe的b.html的src , 利用webbrowser去加载b.html HtmlElementCollection ...
- iOS-运行时机制
这里的两篇运行时的文章感觉还不错. 收藏: 初识iOS运行时RunTime | // TODO: http://www.saitjr.com/ios/objc-runtime.html Objecti ...