SQLAlchemy增删改查基本操作,及SQL基本技能样码(join,group)
练了一天,基本的东东应该有感觉了。
#coding=utf-8 from datetime import datetime from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String, Boolean, DateTime, ForeignKey, ForeignKey, create_engine) from sqlalchemy import (insert, select, update, delete, text, desc, cast, and_, or_, not_) from sqlalchemy.sql import func 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)) ) 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://user:password@1.2.3.4:3306/cookies') metadata.create_all(engine) connection = engine.connect() ''' s = select([cookies]) rp = connection.execute(s) results = rp.fetchall() print results s = cookies.select() rp = connection.execute(s) # print rp.first() for record in rp: print(record.cookie_name) results = rp.fetchall() first_row = results[0] print first_row[1], first_row.cookie_name, first_row[cookies.c.cookie_name] s = select([cookies.c.cookie_name, cookies.c.quantity]) s = s.order_by(desc(cookies.c.quantity)) s = s.limit(4) rp = connection.execute(s) print(rp.keys()) for cookie in rp: print('{} - {}'.format(cookie.quantity, cookie.cookie_name)) s = select([func.sum(cookies.c.quantity)]) rp = connection.execute(s) print(rp.scalar()) # s = select([func.count(cookies.c.cookie_name)]) s = select([func.count(cookies.c.cookie_name).label('inventory_count')]) rp = connection.execute(s) record = rp.first() print(record.keys()) print(record.inventory_count # s = select([cookies]).where(cookies.c.cookie_name == 'chocolate chip') s = select([cookies]).where(cookies.c.cookie_name.like('%chocolate%')) rp = connection.execute(s) for record in rp.fetchall(): print(record.cookie_name) s = select([cookies.c.cookie_name, 'SKU-' + cookies.c.cookie_sku]) for row in connection.execute(s): print(row) s = select([cookies.c.cookie_name, cast((cookies.c.quantity * cookies.c.unit_cost), Numeric(12, 2)).label('inv_cost')]) for row in connection.execute(s): print('{} - {}'.format(row.cookie_name, row.inv_cost)) s = select([cookies]).where( and_(cookies.c.quantity.between(10, 50), cookies.c.cookie_name.contains('chip') ) ) for row in connection.execute(s): print(row.cookie_name) u = update(cookies).where(cookies.c.cookie_name == "chocolate chip") u = u.values(quantity=(cookies.c.quantity + 120)) result = connection.execute(u) print(result.rowcount) s = select([cookies]).where(cookies.c.cookie_name == "chocolate chip") result = connection.execute(s).first() for key in result.keys(): print('{:>20}: {}'.format(key, result[key])) u = delete(cookies).where(cookies.c.cookie_name == "dark chocolate chip") result = connection.execute(u) print(result.rowcount) s = select([cookies]).where(cookies.c.cookie_name == "dark chocolate chip") result = connection.execute(s).fetchall() print(len(result)) customer_list = [ { 'username': 'cookiemon', 'email_address': 'mon@cookie.com', 'phone': '111-111-1111', 'password': 'password' }, { 'username': 'cakeeater', 'email_address': 'cakeeater@cake.com', 'phone': '222-222-2222', 'password': 'password' }, { 'username': 'pieguy', 'email_address': 'guy@pie.com', 'phone': '333-333-3333', 'password': 'password' } ] ins = users.insert() result = connection.execute(ins, customer_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': 2, 'extended_cost': 1.00 }, { 'order_id': 1, 'cookie_id': 3, 'quantity': 12, 'extended_cost': 3.00 } ] result = connection.execute(ins, order_items) ins = insert(orders).values(user_id=2, order_id=2) result = connection.execute(ins) ins = insert(line_items) order_items = [ { 'order_id': 2, 'cookie_id': 1, 'quantity': 24, 'extended_cost': 12.00 }, { 'order_id': 2, 'cookie_id': 4, 'quantity': 6, 'extended_cost': 6.00 } ] result = connection.execute(ins, order_items) columns = [orders.c.order_id, users.c.username, users.c.phone, cookies.c.cookie_name, line_items.c.quantity, line_items.c.extended_cost] cookiemon_orders = select(columns) cookiemon_orders = cookiemon_orders.select_from(orders.join(users).join( line_items).join(cookies)).where(users.c.username == 'cookiemon') result = connection.execute(cookiemon_orders).fetchall() for row in result: print(row) columns = [users.c.username, func.count(orders.c.order_id)] all_orders = select(columns) all_orders = all_orders.select_from(users.outerjoin(orders)) all_orders = all_orders.group_by(users.c.username) result = connection.execute(all_orders).fetchall() for row in result: print(row) def get_orders_by_customer(cust_name, shipped=None, details=False): columns = [orders.c.order_id, users.c.username, users.c.phone] joins = users.join(orders) if details: columns.extend([cookies.c.cookie_name, line_items.c.quantity,line_items.c.extended_cost]) joins = joins.join(line_items).join(cookies) cust_orders = select(columns) cust_orders = cust_orders.select_from(joins) cust_orders = cust_orders.where(users.c.username == cust_name) if shipped is not None: cust_orders = cust_orders.where(orders.c.shipped == shipped) result = connection.execute(cust_orders).fetchall() for row in result: print(row) return result get_orders_by_customer('cakeeater') get_orders_by_customer('cakeeater', details=True) get_orders_by_customer('cakeeater', shipped=True) get_orders_by_customer('cakeeater', shipped=False) get_orders_by_customer('cakeeater', shipped=False, details=True) result = connection.execute("select * from orders").fetchall() print(result) ''' stmt = select([users]).where(text("username='cookiemon'")) print(connection.execute(stmt).fetchall())
SQLAlchemy增删改查基本操作,及SQL基本技能样码(join,group)的更多相关文章
- SQLAlchemy 增删改查 一对多 多对多
1.创建数据表 # ORM中的数据表是什么呢? # Object Relation Mapping # Object - Table 通过 Object 去操纵数据表 # 从而引出了我们的第一步创建数 ...
- SQLAlchemyの增删改查
用a*my写原味sql from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, I ...
- 13,SQLAlchemy 增删改查 一对多 多对多
今天来聊一聊 Python 的 ORM 框架 SQLAlchemy Models 是配置和使用比较简单,因为他是Django自带的ORM框架,也正是因为是Django原生的,所以兼容性远远不如SQLA ...
- SQLAlchemy 增删改查 一对一 多对多
首先要导入SQLAIchemy模块 from sqlalchemy.ect.declaative import declarative_base 创建orm基类 Base = declarative_ ...
- MySQL数据库学习笔记(九)----JDBC的ResultSet接口(查询操作)、PreparedStatement接口重构增删改查(含SQL注入的解释)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- (2)MySQL的增删改查基本操作
数据库增删改查的基本操作(数据文件在data目录下) 数据库的专业术语 1.文件夹:数据库 2.文件:数据表 指令的注意事项 1.用use的时候指令结尾不需要跟一个分号 ‘:’ 2.如果用show或其 ...
- 利用Java针对MySql封装的jdbc框架类 JdbcUtils 完整实现(包含增删改查、JavaBean反射原理,附源码)
最近看老罗的视频,跟着完成了利用Java操作MySql数据库的一个框架类JdbcUtils.java,完成对数据库的增删改查.其中查询这块,包括普通的查询和利用反射完成的查询,主要包括以下几个函数接口 ...
- 偏于SQL语句的 sqlAlchemy 增删改查操作
ORM 江湖 曾几何时,程序员因为惧怕SQL而在开发的时候小心翼翼的写着sql,心中总是少不了恐慌,万一不小心sql语句出错,搞坏了数据库怎么办?又或者为了获取一些数据,什么内外左右连接,函数存储过程 ...
- SQLAlchemy增删改查
sqlalchemy中让MySQL支持中文字符 engine = create_engine("mysql+pymysql://root:mysql8@localhost/mysqltest ...
随机推荐
- Hibernate中的GetCurrentSession()方法
从3.0.1版本开 始,Hibernate增加了SessionFactory.getCurrentSession()方法. 采用getCurrentSession()创建的session在commit ...
- centos 谷歌浏览器安装
首先,这个是坑 http://www.tecmint.com/install-google-chrome-on-redhat-centos-fedora-linux/ 安装会报错,按照错误找到以下资源 ...
- 转:TopN推荐系统——推荐的实现与推荐效果的评价指标
转自:用户推荐系统_python 代码-豆瓣书籍:项亮的<推荐系统实践> import random import math class UserBasedCF: def __init__ ...
- 不知道数据库中表的列类型的前提下,使用JDBC正确的取出数据
概要: 使用jdbc 如果在不知道表结构的情况下,如何读出表信息? 使用ResultSetMetaData; 然后使用getColumnType 获取column 类型 使用getColumnName ...
- glib-2.49.4-msys-x86-staticLib.7z
glib-2.49.4 MSYS 静态库 编译 export LIBFFI_CFLAGS=" -I/usr/local/lib/libffi-3.2.1/include " \ e ...
- Java for LeetCode 236 Lowest Common Ancestor of a Binary Tree
解题思路一: DFS到每个节点的路径,根据路径算出LCA: public class Solution { public TreeNode lowestCommonAncestor(TreeNode ...
- ubuntu下安装mysql
现在的软件越来越好安装,尤其是在ubuntu下安装软件,更是没有技巧,只需要在联网的情况下使用apt-get inatll 即可.在决定安装mysql之前,要先确定系统是否已经安装mysql.如下图: ...
- 【leetcode】Remove Element (easy)
Given an array and a value, remove all instances of that value in place and return the new length. T ...
- 【hadoop2.6.0】通过代码运行程序流程
之前跑了一下hadoop里面自带的例子,现在顺一下如何通过源代码来运行程序. 我懒得装eclipse,就全部用命令行了. 整体参考官网上的:http://hadoop.apache.org/docs/ ...
- HDU 5901 Count primes (1e11内的素数个数) -2016 ICPC沈阳赛区网络赛
题目链接 题意:求[1,n]有多少个素数,1<=n<=10^11.时限为6000ms. 官方题解:一个模板题, 具体方法参考wiki或者Four Divisors. 题解:给出两种代码. ...