sqlalchemy 学习--单表操作
以下所有代码片段都使用了统一的引用,该引用如下:
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, Table
from sqlalchemy.orm import relationship, sessionmaker
engine = create_engine("mysql+pymysql://root:root@localhost/study?charset=utf8", echo=True) # 连接数据库,显示SQL语句
Base = declarative_base() # 创建基类
class Student(Base):
__tablename__ = 'students' # 指定表名
__table_args__ = {
# "mysql_engine":"MyISAM",
"mysql_charset":"utf8"
}
# show create table students 可以查看建表语句;默认是Innodb,lating-1.如果想显示中文需要修改指定建表的类型,同时,engine也要指定编码格式
id = Column(Integer, primary_key=True)
name = Column(String(30))
gender = Column(Integer)
std_id = Column(String(10))
teacher = Column(String(30))
def __str__(self):
return self.name
Base.metadata.create_all(engine) # 创建所有继承自 Base 的类对应的表
sqlslchemy在数据库中创建表之前,会先检查该表是否存在,如果不存在,才会去创建新表
class Student(Base):
__tablename__ = 'students' # 指定表名
id = Column(Integer, primary_key=True)
name = Column(String(30))
gender = Column(Integer)
std_id = Column(String(10))
teacher = Column(String(30))
**math = Column(Integer)**
def __str__(self):
return self.name
虽然新加了一个math
变量(字段),但是由于数据库中已有students
表,所以不会去创建新表,match
字段也就不存在
插入数据
Session = sessionmaker(bind=engine) # 获取 Session类
ses = Session() # 获取session对象
zhangsan = Student(name="zhangsan", gender=1, std_id='XS331', teacher='hanmeimei', math=90)
lisi = Student(name="lisi", gender=1, std_id='XS332', teacher='hanmeimei', math=10)
wangwu = Student(name="wangwu", gender=0, std_id='XS333', teacher='lilei', math=60)
zhaoliu = Student(name="zhaoliu", gender=0, std_id='XS337', teacher='lilei', math=80)
ses.add(zhangsan) # 单条添加
ses.add_all([lisi, wangwu, zhaoliu]) # 批量添加
ses.commit()
修改数据
zhangsan = ses.query(Student).filter_by(name='zhangsan').first()
zhangsan.math = 91
ses.commit()
也可以在还创建数据的时候,修改
liqi = Student(name="liqi", gender=1, std_id='XS335', teacher='xiadonghai', math=100)
ses.add(liqi)
liqi = ses.query(Student).filter_by(name='liqi').first()
liqi.gender = 0
ses.commit()
liqi = Student(name="liqi", gender=1, std_id='XS335', teacher='xiadonghai', math=100)
liqi.gender = 0
ses.add(liqi)
ses.commit()
sess.query(Student).filter_by(name='liming').update({'gender':0})
sess.commit()
删除
# result = sess.query(Student).filter(Student.id == 1 ).delete()
# sess.commit()
# result = sess.query(Student).filter(Student.id == 2 ).first()
# sess.delete(result)
# sess.commit()
查询
# = 操作符
# students_99 = sess.query(Student).filter_by(name ='zhangsan').all()
# students_100 = sess.query(Student).filter(Student.name == 'zhangsan').all()
# for i in students_100:
# print(i.name)
# != 操作符
# student_101 = sess.query(Student).filter_by(name != 'liming').all() # error
# student_98 = sess.query(Student).filter(Student.name != 'liming').all()
# for i in student_98:
# print(i.name)
# > ,<, <=, >=, 操作符
# student_60 = sess.query(Student).filter(Student.math > 10).all()
# student_61= sess.query(Student).filter_by(math>10).all() # error
# student_62 = sess.query(Student).filter(Student.math < 100).all()
# student_63 = sess.query(Student).filter(Student.math <= 90).all()
# student_64 = sess.query(Student).filter(Student.math >= 90).all()
# student_64 = sess.query(Student).filter(Student.math <> 90).all() # error
# for i in student_60:
# print(i.math)
# for i in student_62:
# print(i.math)
# for i in student_63:
# print(i.math)
# for i in student_64:
# print(i.math)
# 根据主键获取对象
# students_1 = sess.query(Student).get(1)
# print(students_1
# value指定要获取的字段 返回的是生成器
# students_3 = sess.query(Student).value(Student.name)
# print(students_3)
# values 指定多个字段 返回的是生成器
# students_3_2 = sess.query(Student).values(Student.id,Student.name)
# print(students_3_2)
# for i in students_3_2:
# print(i)
# 一次获取多个字段值
# students_4 = sess.query(Student.name,Student.gender).all()
# print(students_4)
# for i in students_4:
# print(i)
# 后续添加的方式选择要得到的字段结果
# students_5 = sess.query(Student.name).add_columns(Student.gender).all()
# print(students_5)
# student_6 = sess.query(Student).filter_by(name="王大麻子").one()
# print(student_6)
# 字段别名
# student_7 = sess.query(Student.name.label('std_name')).all()
# print(student_7)
# for i in student_7:
# print(i.std_name)
# print(i[0]) # 第二种取值方式
# student_8 = sess.query(Student.name).all()
# print(student_8)
# for i in student_8:
# print(i.name)
# print(i[0])
# 分页
# student_10 = sess.query(Student).limit(2).offset(1).all()
# student_11 = sess.query(Student).offset(1).limit(2).all()
# student_12 = sess.query(Student)[1:3]
# for i in student_10:
# print(i.id)
# for i in student_11:
# print(i.id)
# for i in student_12:
# print(i.id)
# filter 和 filter_by
# student_13 = sess.query(Student).filter_by(id=1).one_or_none()
# student_14 = sess.query(Student).filter(Student.id == 1).one_or_none()
# print(student_13)
# print(student_14)
# chain 链式调用
# student_15 = sess.query(Student).filter_by(gender=1).filter(Student.math>80).all()
# # student_15_2 = sess.query(Student).filter_by(gender=1).filter_by(math>80).all() # error
# student_16 = sess.query(Student).filter(Student.gender == 1).filter(Student.math>80).all()
# for i in student_15:
# print(i.name)
# for i in student_16:
# print(i.name)
# like 操作符 % 代表任意多个字符 _ 代表一个字符
# student_17 = sess.query(Student).filter(Student.name.like("%i%")).all()
# for i in student_17:
# print(i.name)
# student_17_2 = sess.query(Student).filter(Student.name.like("%i_i")).all()
# for i in student_17_2:
# print(i.name)
# not like
# student_70 = sess.query(Student).filter(~Student.name.like("%i_i")).all()
# student_71 = sess.query(Student).filter(Student.name.notlike("%i_i")).all()
# for i in student_70:
# print(i.name)
# print(student_70 == student_71)
# in 操作符
# student_18 = sess.query(Student).filter(Student.name.in_(['zhangsan','lisi','wangwu'])).all()
# for i in student_18:
# print(i.name)
# not in
# student_19 = sess.query(Student).filter(~Student.name.in_(['lisi'])).all()
# student_19_2 = sess.query(Student).filter(Student.name.notin_(['lisi'])).all()
# for i in student_19:
# print(i.name)
# print(student_19 == student_19_2)
# 是否为null
# student_20 = sess.query(Student).filter(Student.name != None).all()
# student_21 = sess.query(Student).filter(~Student.name.is_(None)).all()
# student_22 = sess.query(Student).filter(Student.name.isnot(None)).all()
# student_21_3 = sess.query(Student).filter(Student.name.is_('zhangsan')).all() # error
# student_21_2 = sess.query(Student).filter(Student.name.is_(1)).all()
# for i in student_20:
# print(i.name)
# print(student_20 == student_21 == student_22)
# student_23 = sess.query(Student).filter(Student.math.is_(90)).all()
# student_24 = sess.query(Student).filter(Student.math == None).all()
# 类别名
# flower = aliased(Student)
# student_9 = sess.query(flower.name).all()
# print(student_9)
# and
# student_25 = sess.query(Student).filter(Student.gender == 1, Student.math > 70).all()
# student_26 = sess.query(Student).filter(and_(Student.gender == 1, Student.math > 70)).all() # 别忘了引入该方法
# student_27 = sess.query(Student).filter(Student.gender == 1).filter(Student.math > 70).all()
# for i in student_25:
# print(i.name)
# print(student_25 == student_26 == student_27)
# or
# student_28 = sess.query(Student).filter(or_(Student.gender == 1, Student.math > 80)).all()
# for i in student_28:
# print(i.name)
# 错误用法
# error_1 = sess.query(Student).filter_by(and_(Student.id == 1, Student.name == 'lisi')).first()
# error_2 = sess.query(Student).filter_by(and_(id=1, name='lisi')).first()
# error_3 = sess.query(Student).filter(and_(id=1, name='lisi')).first()
# one 有且只有一个,否则报错
# student_30 = sess.query(Student).filter(Student.id == 1).one()
# print(student_30)
# 可以只有一个或者没有,不能为多个结果,否则报错
# student_31 = sess.query(Student).filter(Student.id == 10).one_or_none()
# print(student_31)
# text 原生sql条件语句
# student_31 = sess.query(Student).filter(text("name='lisi'")).first() # 注意值为字符串时的写法
# student_32 = sess.query(Student).filter(text("id=1")).first() # 注意值为 数字 的写法
# student_31 = sess.query(Student).filter(text("id>1 and math>10")).all()
# for i in student_31:
# print(i.name)
# order_by 排序
# student_33 = sess.query(Student).filter(text("math >= 10")).order_by(~text("math")).all() # 逆序
# student_33_2 = sess.query(Student).filter(text("math >= 10")).order_by(text("math")).all() # 顺序
# student_33_2_1 = sess.query(Student).filter(text("math >= 10")).order_by(desc(text("math"))).all() # 逆序
# student_33_3 = sess.query(Student).order_by(desc(Student.math)).all() # 逆序
# student_33_4 = sess.query(Student).order_by(Student.math.desc()).all() # 逆序
# student_33_5 = sess.query(Student).order_by(~Student.math).all() # 逆序
# student_33_6 = sess.query(Student).order_by(Student.math).all() # 顺序
# print(student_31)
# print(student_32)
# print("___"* 30)
# for i in student_33:
# print(i.math)
# print("___"* 30)
# for i in student_33_2:
# print(i.math)
# for i in student_33_3:
# print(i.math)
# for i in student_33_4:
# print(i.math)
# for i in student_33_5:
# print(i.math)
# for i in student_33_6:
# print(i.math)
# text 插入变量
# student_34 =sess.query(Student).filter(text("gender=:sex and math>:score")).params(sex=1, score=1).all()
# for i in student_34:
# print(i.name)
# from_statement 原生sql语句
# student_35 = sess.query(Student).from_statement(text("select * from students where id=:id")).params(id=1).one()
# student_36 = sess.query(Student).from_statement("select * from students where math>:score").params(score=10).all()
# student_36_1 = sess.query(Student).from_statement("select * from students where math>10").all()
# print(student_35)
# for i in student_36:
# print(i.name)
# print(student_36 == student_36_1)
# count
# student_38 = sess.query(Student).filter_by(gender=1).count()
# student_38_2 = sess.query(func.count(Student.name),Student.name).group_by(Student.name).all()
# student_38_3 = sess.query(func.count(Student.name),Student.gender).group_by(Student.gender).all()
# print(student_38_2)
# print(student_38_3)
# group_by 分组
# student_39 = sess.query(Student).group_by(Student.gender == 1).count()
# print(student_39)
# having
# student_39_1 = sess.query(Student).group_by(Student.gender == 1).having(Student.math>60).all()
# for i in student_39_1:
# print(i)
# distinct
# student_40 = sess.query(distinct(Student.name)).all()
# for i in student_40:
# print(i)
sqlalchemy 学习--单表操作的更多相关文章
- sqlalchemy 学习-- 多表操作
一对多:一对一 # one -- many class Students(Base): __tablename__ = "students" sid = Column(Intege ...
- 学习MySQL之单表操作(二)
##单表操作 ##创建表 CREATE TABLE t_employee( empno ), ename ), job ), MGR ), Hiredate DATE DEFAULT '0000-00 ...
- day 46 Django 学习3 数据库单表操作以及反向解析
前情提要: Django 已经学了不少了, 今天学习链接数据库的操作.以及相关的反向解析等 一:反向解析 1:反向解析模板层 跳转时设定url会随着前面的路由改变而改变 2:反向解析之 ...
- sqlalchemy模块介绍、单表操作、一对多表操作、多对多表操作、flask集成.
今日内容概要 sqlalchemy介绍和快速使用 单表操作增删查改 一对多 多对多 flask集成 内容详细 1.sqlalchemy介绍和快速使用 # SQLAlchemy是一个基于 Python实 ...
- Django学习笔记(7)——单表操作和多表操作
单表操作 1,创建模型 创建名为book的APP,在book下的models.py中创建模型: from django.db import models # Create your models he ...
- hibernate学习笔记(6)组件属性以及单表操作
组件属性:实体类中的某个属性属于用户自定义类的对象: 作用:将两个实体类合并在一起组建成一个表 在hbm.xml文件中配置: 格式: <component name="取的名字&quo ...
- python 全栈开发,Day71(模型层-单表操作)
昨日内容回顾 1. {% include '' %} 2. extend base.html: <html> ..... ..... ..... {% block content%} {% ...
- ORM 简介 单表操作
cls超 Django基础五之django模型层(一)单表操作 本节目录 一 ORM简介 二 单表操作 三xxx 一 ORM简介 MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型 ...
- Django基础五之django模型层(一)单表操作
一 ORM简介 MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可以轻松更换数据库,这极大的减轻了开发人 ...
随机推荐
- sp_settriggerorder 设置触发器执行顺序
sp_settriggerorder (Transact-SQL) 本主题适用于:SQL Server(从 2008 开始)Azure SQL 数据库Azure SQL 数据仓库并行数据仓库 ...
- FFMPEG 中dts和pts区别
FFMPEG 中dts和pts区别 CopyFrom:http://www.cnblogs.com/yinxiangpei/articles/3892982.html 视频的显示和存放原理 对 ...
- ERROR hive.HiveConfig: Could not load org.apache.hadoop.hive.conf.HiveConf. Make sure HIVE_CONF_DIR is set correctly.
Sqoop导入mysql表中的数据到hive,出现如下错误: ERROR hive.HiveConfig: Could not load org.apache.hadoop.hive.conf.Hi ...
- Servlet --简单用户留言系统
1.创建用户表和留言表 2.编写数据库连接工具类 public class SqlserverDBConn { private Statement stmt; private Connection c ...
- Alpha预乘-混合与不混合[转]
作者:John McDonald,于2013年1月31日上午07:57发布 标签: GameWorks专家开发人员 Alpha Blending几乎是每个3D应用程序的一小部分,但却很重要.从概念上 ...
- python学习之----遍历单个域名和随机数
实现“维基百科六度分隔理论”的查找方法.也就是说,我们要实现从埃里克 · 艾德尔的词条页面(https://en.wikipedia.org/wiki/Eric_Idle)开始,经过最少的链接点击次数 ...
- python学习之----获取标签属性
到目前为止,我们已经介绍过如何获取和过滤标签,以及获取标签里的内容.但是,在网 络数据采集时你经常不需要查找标签的内容,而是需要查找标签属性.比如标签<a> 指向 的URL 链接包含在hr ...
- this绑定丢失的问题
在之前的一篇文章<this绑定>中已经说过this绑定的四种情况,也谈到了this绑定丢失的问题,但是没有解释为什么会出现this绑定的丢失,最近在多次阅读关于this绑定方面的文章之后, ...
- 剑指offer(一):二维数组中的查找
说明: 1.本系列是根据<剑指Offer>这个系列做的一个小笔记. 2.直接动力是因为师兄师姐找工作很难,而且机械出生的我面试算法更难. 3.刚开始准备刷LeetCode.LintCode ...
- 从入门到熟悉 HTTPS 的 9 个问题
九个问题从入门到熟悉HTTPS 最近一边做毕设一边学习编程.前两天她问我 HTTPS 的问题,本来想直接扔一篇网上的教程给她.后来想了一下,那些文章大多直接介绍概念, 对新手不太友好,于是我干脆亲自给 ...