这部门内容比较简单,立存。

#coding=utf-8

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

metadata = MetaData()

cookies = Table('cookies', metadata,
                Column('cookie_id', Integer(), primary_key=True),
                Column('cookie_name', String(50), index=True),
                Column('cookie_recipe_url', String(255)),
                Column('cookie_sku', String(55)),
                Column('quantity', Integer()),
                Column('unit_cost', Numeric(12, 2)),
                CheckConstraint('quantity >= 0', name='quantity_positive')
                )

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

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

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

engine = create_engine('mysql+pymysql://u:p@ip:3306/cookies')
metadata.create_all(engine)
connection = engine.connect()

def ship_it(order_id):
    s = select([line_items.c.cookie_id, line_items.c.quantity])
    s = s.where(line_items.c.order_id == order_id)
    transaction = connection.begin()
    cookies_to_ship = connection.execute(s)
    try:
        for cookie in cookies_to_ship:
            u = update(cookies).where(cookies.c.cookie_id==cookie.cookie_id)
            u = u.values(quantity = cookies.c.quantity - cookie.quantity)
            result = connection.execute(u)
        u = update(orders).where(orders.c.order_id == order_id)
        u = u.values(shipped=True)
        result = connection.execute(u)
        print("Shipped order ID: {}".format(order_id))
        transaction.commit()
    except IntegrityError as error:
        transaction.rollback()
        print(error)

'''
ins = insert(users).values(
    username="cookiemon",
    email_address="mon@cookie.com",
    phone="111-111-1111",
    password="password"
    )
try:
    result = connection.execute(ins)
except IntegrityError as error:
    pass

ins = cookies.insert()
inventory_list = [
    {
        'cookie_name': 'chocolate chip',
        'cookie_recipe_url': 'http://some.aweso.me/cookie/recipe.html',
        'cookie_sku': 'CC01',
        'quantity': '12',
        'unit_cost': '0.50'
    },
    {
        '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'
    }
    ]
result = connection.execute(ins, inventory_list)

ins = insert(orders).values(user_id=1, order_id='1')
result = connection.execute(ins)
ins = insert(line_items)
order_items = [
    {
        'order_id': 1,
        'cookie_id': 1,
        'quantity': 9,
        'extended_cost': 4.50
    }
    ]
result = connection.execute(ins, order_items)

ins = insert(orders).values(user_id=1, order_id='2')
result = connection.execute(ins)
ins = insert(line_items)
order_items = [
    {
        'order_id': 2,
        'cookie_id': 1,
        'quantity': 4,
        'extended_cost': 1.50
    },
    {
        'order_id': 2,
        'cookie_id': 2,
        'quantity': 1,
        'extended_cost': 4.50
    }
    ]
result = connection.execute(ins, order_items)

ship_it(1)
s = select([cookies.c.cookie_name, cookies.c.quantity])
connection.execute(s).fetchall()
'''
ship_it(20)

SQLAlchemy Core中的异常及事务处理样码的更多相关文章

  1. ASP.Net Core中处理异常的几种方法

    本文将介绍在ASP.Net Core中处理异常的几种方法 1使用开发人员异常页面(The developer exception page) 2配置HTTP错误代码页 Configuring stat ...

  2. .net core 的图片处理及二维码的生成及解析

    写代码这事,掐指算来已经十有余年. 从html到css到javascript到vbscript到c#,从兴趣到职业,生活总是失落与惊喜并存. 绝大部分时候,出发并不是因为知道该到哪里去,只是知道不能再 ...

  3. TransactionScope事务处理方法介绍及.NET Core中的注意事项

    作者:依乐祝 原文链接:https://www.cnblogs.com/yilezhu/p/10170712.html 今天在写CzarCms的UnitOfWork的使用使用到了这个Transacti ...

  4. TransactionScope事务处理方法介绍及.NET Core中的注意事项 SQL Server数据库漏洞评估了解一下 预热ASP.NET MVC 的VIEW [AUTOMAPPER]反射自动注册AUTOMAPPER PROFILE

    TransactionScope事务处理方法介绍及.NET Core中的注意事项   作者:依乐祝 原文链接:https://www.cnblogs.com/yilezhu/p/10170712.ht ...

  5. 【转】TransactionScope事务处理方法介绍及.NET Core中的注意事项

    什么是TransactionScope呢? TransactionScope作为System.Transactions的一部分被引入到.NET 2.0.同时SqlClient for .NET Cor ...

  6. ASP.NET Core中,UseDeveloperExceptionPage扩展方法会吃掉异常

    在ASP.NET Core中Startup类的Configure方法中,有一个扩展方法叫UseDeveloperExceptionPage,如下所示: // This method gets call ...

  7. 如何处理Entity Framework / Entity Framework Core中的DbUpdateConcurrencyException异常(转载)

    1. Concurrency的作用 场景有个修改用户的页面功能,我们有一条数据User, ID是1的这个User的年龄是20, 性别是female(数据库中的原始数据)正确的该User的年龄是25, ...

  8. Linux中生成Core Dump系统异常信息记录文件的教程

    Linux中生成Core Dump系统异常信息记录文件的教程 http://www.jb51.net/LINUXjishu/473351.html

  9. 项目开发中的一些注意事项以及技巧总结 基于Repository模式设计项目架构—你可以参考的项目架构设计 Asp.Net Core中使用RSA加密 EF Core中的多对多映射如何实现? asp.net core下的如何给网站做安全设置 获取服务端https证书 Js异常捕获

    项目开发中的一些注意事项以及技巧总结   1.jquery采用ajax向后端请求时,MVC框架并不能返回View的数据,也就是一般我们使用View().PartialView()等,只能返回json以 ...

随机推荐

  1. HDU 2855 斐波那契+矩阵快速幂

    http://acm.hdu.edu.cn/showproblem.php?pid=2855 化简这个公式,多写出几组就会发现规律 d[n]=F[2*n] 后面的任务就是矩阵快速幂拍一个斐波那契模板出 ...

  2. Qt 官方一键动态发布技能

    苦找了好几天动态库,程序可以运行了,结果没有图标还是少了运行库很苦恼,发现Qt 官方有一键动态发布功能感觉自己萌萌的,来自qt吧亲测可用. 集成开发环境 QtCreator 目前生成图形界面程序 ex ...

  3. Eclipse中项目红叉但找不到错误解决方法

    首先windows-show view-problems 根据地址查找错误 若提示: Description    Resource    Path    Location    TypeJava c ...

  4. 腾讯云环境配置之PHP5.6.3 + redis扩展 稳定版

    腾讯云环境配置之PHP5.6.3 + redis扩展 稳定版 时间:2015-01-18 01:41来源:linux.it.net.cn 作者:IT   #由于上文装过yum groupinstall ...

  5. oracle数据库常用plsql语句

    (一)oracle中常用的数据类型 (二)PL-sql基本语法 1.创建数据库表.删除数据库表 create table table1--创建表 ( field1 number(8), field2 ...

  6. Windows下安装Maven

    上篇文章刚说到Linux下安装maven的过程,有时候为了适合在本地构建项目开发,然后上传到远程服务器执行,需要在本地构建maven项目,那么一般就是在Windows下构建maven项目并导入到我们的 ...

  7. cxGrid 速度

    在做AdoHelper实用程序的时候,我用了DevExpress的cxGrid控件.在此之前用的是dbgrid,考虑到不能把所有的数据都拉到本地,我用了动态生成的select top 500的命令.这 ...

  8. CXGrid的使用技巧

    CXGrid的使用技巧 ========================================================================== 在主从TableView中 ...

  9. 和我一起学python,基本概念 (life is short ,we need python)

    作者:tobecrazy  出处:http://www.cnblogs.com/tobecrazy 欢迎转载,转载请注明出处.thank you! 基本概念 : 常量: 常量名全部大写,如PI 变量: ...

  10. java一维数组

    1.通过数组名进行赋值,其实质是引用 比如数组array1和数组array2 若执行array2=array1,实际上将array1的引用传递给array2,array1和array2 最后都指向同一 ...