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下使用ffmpeg将amr转成mp3
说明:AMR格式是智能手机上的常用音频文件格式,比MP3格式的压缩比大.同样时长的AMR文件大概是MP3的十分之一,所以在移动互联项目中应用比较广泛.但目前AMR格式在个人电脑上应用较少,所以目前大部 ...
- 一个按比特位拷贝数据的函数copybits
一个按比特位拷贝数据的函数 没有进行特别的优化.其实还可以在拷贝源开始位置和目标开始位置是2的整数倍位置的时候进行优化. 说明 这个函数用于从src数组首地址跳过sbb个字节,又跳过ssb个比特位,拷 ...
- 如何用phpstorm编辑远程项目
背景介绍:LAMP开发是很多公司喜欢采用的技术组合,故而做php开发,使用linux环境也是很多公司的要求.本文就来介绍下如何在windows下,使用phpstorm集成开发环境,来开发放在linux ...
- SVN钩子说明
post-commit在提交完成,成功创建版本之后执行该钩子,提交已经完成,不可更改,因此本脚本的返回值被忽略. post-lock对文件进行加锁操作之后执行该脚本 post-revprop-chan ...
- 报错:No package erlang available
问题 yum install erlang 报错:No package erlang available 同样的,如果我们在安装nginx的时候出现"No package nginx ava ...
- dango foreign key 指定被引用模型的字段
用 to_field pool_no = models.ForeignKey('SimCardPool', verbose_name=u'卡池编号', db_column='pool_no', to_ ...
- 解决file_get_contents无法请求https连接的方法
PHP.ini默认配置下,用file_get_contents读取https的链接,就会报如下错误,本文给出解决方法 错误: Warning: fopen() [function.fopen]: Un ...
- When building php 5.3, if you get the following error:
buildconf: You need autoconf 2.59 or lower to build this version of PHP. You are currently trying to ...
- 深入浅出Mybatis-与Spring集成
单独使用mybatis是有很多限制的(比如无法实现跨越多个session的事务),而且很多业务系统本来就是使用spring来管理的事务,因此mybatis最好与spring集成起来使用. 前置要求 版 ...
- spring + myBatis 常见错误:@Autowired注解失败
今天配置spring+myBatis的时候,使用注解@Autowired把持久层dao注入service层的时候总是报错. 查了好久才发现,居然是配置文件路径写错了.basepackge的路径一定要正 ...