1、unique = True 表示启动唯一索

2、有add 必须有commit这样数据才会提交

3、ORM功能

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) Base = declarative_base() # 创建单表
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
extra = Column(String(16)) __table_args__ = (
UniqueConstraint('id', 'name', name='uix_id_name'),
Index('ix_id_name', 'name', 'extra'),
) # 一对多
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True)
caption = Column(String(50), default='red', unique=True) class Person(Base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=True)
favor_id = Column(Integer, ForeignKey("favor.nid")) # 多对多
class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False)
port = Column(Integer, default=22) class Server(Base):
__tablename__ = 'server' id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False) class ServerToGroup(Base):
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(Integer, ForeignKey('server.id'))
group_id = Column(Integer, ForeignKey('group.id')) def init_db():
Base.metadata.create_all(engine) def drop_db():
Base.metadata.drop_all(engine)

建表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) Base = declarative_base() # 创建单表
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
extra = Column(String(16)) __table_args__ = (
UniqueConstraint('id', 'name', name='uix_id_name'),
Index('ix_id_name', 'name', 'extra'),
) def __repr__(self):
return "%s-%s" %(self.id, self.name) # 一对多
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True)
caption = Column(String(50), default='red', unique=True) def __repr__(self):
return "%s-%s" %(self.nid, self.caption) class Person(Base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=True)
favor_id = Column(Integer, ForeignKey("favor.nid"))
# 与生成表结构无关,仅用于查询方便
favor = relationship("Favor", backref='pers') # 多对多
class ServerToGroup(Base):
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(Integer, ForeignKey('server.id'))
group_id = Column(Integer, ForeignKey('group.id'))
group = relationship("Group", backref='s2g')
server = relationship("Server", backref='s2g') class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False)
port = Column(Integer, default=22)
# group = relationship('Group',secondary=ServerToGroup,backref='host_list') class Server(Base):
__tablename__ = 'server' id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False) def init_db():
Base.metadata.create_all(engine) def drop_db():
Base.metadata.drop_all(engine) Session = sessionmaker(bind=engine)
session = Session() 表结构 + 数据库连接

连接db

#增
obj = Users(name="alex0", extra='sb')
session.add(obj)
session.add_all([
Users(name="alex1", extra='sb'),
Users(name="alex2", extra='sb'),
])
session.commit()
#删
session.query(Users).filter(Users.id > 2).delete()
session.commit()
#改
session.query(Users).filter(Users.id > 2).update({"name" : ""})
session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + ""}, synchronize_session=False)
session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()
#查
ret = session.query(Users).all()
ret = session.query(Users.name, Users.extra).all()
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter_by(name='alex').first() ret = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(User.id).all() ret = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()
#其他
# 条件
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()
from sqlalchemy import and_, or_
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
ret = session.query(Users).filter(
or_(
Users.id < 2,
and_(Users.name == 'eric', Users.id > 3),
Users.extra != ""
)).all() # 通配符
ret = session.query(Users).filter(Users.name.like('e%')).all()
ret = session.query(Users).filter(~Users.name.like('e%')).all() # 限制
ret = session.query(Users)[1:2] # 排序
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all() # 分组
from sqlalchemy.sql import func ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
func.max(Users.id),
func.sum(Users.id),
func.min(Users.id)).group_by(Users.name).all() ret = session.query(
func.max(Users.id),
func.sum(Users.id),
func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all() # 连表 ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all() ret = session.query(Person).join(Favor).all() ret = session.query(Person).join(Favor, isouter=True).all() # 组合
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all() q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()

数据库操作

条件用 filter单值用filter_by

4、示例代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#coding:utf8
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
print(sqlalchemy.__version__) engine = create_engine('mysql+pymysql://sysadmin:password01!@10.10.8.12:3306/q2') Base = declarative_base()#生成一个SQLORM基类 class User(Base):
__tablename__ = 'sqlalchemydemo' id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(40))
fullname = Column(String(40))
password = Column(String(40)) def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password) Base.metadata.create_all(engine) #创建所有表结构
# Base.metadata.drop_all(engine) # 删除所有表
# ed_user = User(name='xiaoyu', fullname='Xiaoyu Liu', password='123')
# print(ed_user)
# #这两行触发sessionmaker类下的__call__方法,return得到 Session实例,赋给变量session,所以session可以调用Session类下的add,add_all等方法
MySession = sessionmaker(bind=engine)
session = MySession() # session.add(ed_user) ##添加数据
# our_user = session.query(User).filter_by(name='ed').first()
# SELECT * FROM users WHERE name="ed" LIMIT 1;
# session.add_all([
# User(name='alex', fullname='Alex Li', password='456'),
# User(name='alex', fullname='Alex old', password='789'),
# User(name='peiqi', fullname='Peiqi Wu', password='sxsxsx')])
#
# session.commit() #print(">>>",session.query(User).filter_by(name='ed').first())
# print(session.query(User).all()) #表内容 # for row in session.query(User).order_by(User.id):
# print(row)
# for row in session.query(User).filter(User.name.in_(['alex', 'wendy', 'jack'])):#这里的名字是完全匹配
# print(row)
# for row in session.query(User).filter(~User.name.in_(['ed', 'wendy', 'jack'])):
# print(row)
# print(session.query(User).filter(User.name == 'ed').count())
from sqlalchemy import and_, or_ # for row in session.query(User).filter(and_(User.name == 'ed', User.fullname == 'Ed Jones')):
# print(row)
for row in session.query(User).filter(or_(User.name == 'ed', User.fullname == 'wendy')):
print(row)

lone

#!/usr/bin/env python
# -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine('mysql+pymysql://sysadmin:password01!@10.10.8.12:3306/q2') Base = declarative_base() class Son(Base):
__tablename__ = 'son'
id = Column(Integer, primary_key=True)
name = Column(String(32))
age = Column(String(16)) father_id = Column(Integer, ForeignKey('father.id'))
# father = relationship('Father') # __table_args__ = (
# UniqueConstraint('id', 'name', name='uix_id_name'),
# Index('ix_id_name', 'name', 'extra'),
# )
# class Father(Base):
__tablename__ = 'father' id = Column(Integer, primary_key=True)
name = Column(String(32))
age = Column(String(16))
son = relationship('Son', backref = 'father') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine)
session = Session() # ret3 = session.query(Father).filter_by(id=1).all()
# ret4 = session.query(Father).filter_by(id=4).first()
# for ii in ret4.son:
# print(ii.name) # s1 = session.query(Son).filter_by(id=1).first()
# print(s1.father.name,s1.name) ret4 = session.query(Father).filter_by(id=4).first()
w4 = Son(name = 'little alvin4',age = 5)
ret4.son.append(w4)
session.add(ret4)
session.commit() # print(ret3)
# for i in ret3:
# print(i.name) #
# ret1 = session.query(Father.name.label('kkk'), Son.name.label('ppp')).join(Son)
#
# ret = session.query(Father.name.label('kkk'), Son.name.label('ppp')).join(Son).all()
# print(ret1)
# print(ret)
#
# print(len(ret))
# for ii in ret:
# print(ii)
# # f1 = Father(name='alvin4', age=50)
# w1 = Son(name='little alvin1', age=4, father_id = 2)
# w2 = Son(name='little alvin2', age=5, father_id = 2)
# #
# # f1.son = [w1, w2]
# # session.add(f1)
#
# session.add_all([w1,w2])
# session.commit()

one2many

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine('mysql+pymysql://sysadmin:password01!@10.10.8.12:3306/q2?charset=utf8')
Base = declarative_base() class Men_to_Wemon1(Base):
__tablename__ = 'men_to_wemon1'
nid = Column(Integer, primary_key=True)
men_id = Column(Integer, ForeignKey('men1.id'))
women_id = Column(Integer, ForeignKey('women1.id')) class Men1(Base):
__tablename__ = 'men1'
id = Column(Integer, primary_key=True)
name = Column(String(32))
age= Column(String(16)) class Women1(Base):
__tablename__ ='women1'
id = Column(Integer, primary_key=True)
name = Column(String(32))
age= Column(String(16))
bf=relationship("Men1",secondary=Men_to_Wemon1.__table__,backref='gf') Base.metadata.create_all(engine)
#
Session = sessionmaker(bind=engine)
session = Session()
#
# m1=Men1(name='alex',age=18)
# m2=Men1(name='wusir',age=18)
# w1=Women1(name='如花',age=40)
# w2=Women1(name='铁锤',age=45) # t1 = Men_to_Wemon1(men_id=1,women_id=2) m1 = session.query(Men1).filter_by(id = 2).first()
w1 = session.query(Women1).all()
m1.gf=w1
# m1.gf=[w1,w2]
# w1.bf=[m1,m2]
session.add_all([m1,])
# session.add_all([m1,m2,w1,w2])
# session.add(t1)
session.commit()

many2many

#!/usr/bin/env python
# -*- coding:utf-8 -*- from sqlalchemy import create_engine, and_, or_, func, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship engine = create_engine('mysql+pymysql://sysadmin:password01!@10.10.8.12:3306/q2?charset=utf8') Base = declarative_base() # 生成一个SqlORM 基类 class HostToGroup(Base):
__tablename__ = 'host_2_group'
nid = Column(Integer, primary_key=True)
host_id = Column(Integer, ForeignKey("host.id"))
group_id = Column(Integer, ForeignKey("group.id")) class Host(Base):
__tablename__ = 'host' id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False)
ip_addr = Column(String(128), unique=True, nullable=False)
port = Column(Integer, default=22)
group = relationship('Group',
secondary=HostToGroup.__table__,
backref='host_list') # group =relationship("Group",back_populates='host_list')
def __repr__(self):
return "<id=%s,hostname=%s, ip_addr=%s>" % (self.id,
self.hostname,
self.ip_addr) class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False) def __repr__(self):
return "<id=%s,name=%s>" % (self.id, self.name) Base.metadata.create_all(engine) # 创建所有表结构 if __name__ == '__main__':
SessionCls = sessionmaker(bind=engine)
session = SessionCls()
#
# g1 = Group(name='g1')
# g2 = Group(name='g2')
# g3 = Group(name='g3')
# g4 = Group(name='g4')
# session.add_all([g1,g2,g3,g4])
# h1 = Host(hostname='h1',ip_addr='192.168.1.56')
# h2 = Host(hostname='h2',ip_addr='192.168.1.57',port=10000)
# h3 = Host(hostname='ubuntu',ip_addr='192.168.1.58',port=10000)
#
# h1.group=[g2,g4]
# session.add_all([h1,h2,h3])
# session.commit() # groups = session.query(Group).all()
# h2 = session.query(Host).filter(Host.hostname=='h2').first()
# h2.group = groups[:-1]
# print("===========>",h2.group) g4 = session.query(Group).filter(Group.name=='g4').first()
print(g4)
obj1 = session.query(Host).filter(Host.hostname=='h1').update({'port':444})
obj2 = session.query(Host).filter(Host.hostname=='h1').first() # g4.host_list.append(obj2)
obj2.group.append(g4) #
# obj2= session.query(Host).filter(Host.hostname=='h1').first()
# print("h1:",obj2.group)
# print("g:",g4.host_list ) session.commit()

many2many2

day40--mysql step4 SQLAlchemy的更多相关文章

  1. mysql和SQLAlchemy

    mysql和SQLAlchemy 一.MySQL分组查询 1.1 MySQL对数据表进行分组查询(GROUP BY) 1.GROUP BY基本语法格式: GROUP BY关键字可以将查询结果按照某个字 ...

  2. 将pandas的DataFrame数据写入MySQL数据库 + sqlalchemy

    将pandas的DataFrame数据写入MySQL数据库 + sqlalchemy import pandas as pd from sqlalchemy import create_engine ...

  3. MySQL、sqlalchemy、pymysql、mysqldb、DBAPI之间关系梳理(终于明白了)

    MySQL.sqlalchemy.pymysql.mysqldb.DBAPI之间关系梳理(终于明白了) python3不再支持mysqldb 请用pymysql和mysql.connector 问题背 ...

  4. 用 Flask 来写个轻博客 (3) — (M)VC_连接 MySQL 和 SQLAlchemy

    目录 目录 前文列表 扩展阅读 前言 Models 模型 SQLAlchemy 安装 SQLAlchemy 安装 Mysql 建立 SQLAlchemy 和 Mysql 的连接 前文列表 用 Flas ...

  5. python笔记-13 mysql与sqlalchemy

    一.RDBMS relational database management system 关系型数据库引入 1.数据库的意义 更有效和合理的存储读取数据的一种方式 关系模型基础上的数据库 -> ...

  6. 冰冻三尺非一日之寒-mysql(orm/sqlalchemy)

    第十二章  mysql ORM介绍    2.sqlalchemy基本使用 ORM介绍: orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似pyt ...

  7. day12---python mysql pymsql sqlalchemy ORM

    RDBMS 术语 在我们开始学习MySQL 数据库前,让我们先了解下RDBMS的一些术语: 数据库: 数据库是一些关联表的集合.. 数据表: 表是数据的矩阵.在一个数据库中的表看起来像一个简单的电子表 ...

  8. Python操作MySQL之SQLAlchemy

      SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结 ...

  9. Python之路第十二天,高级(5)-Python操作Mysql,SqlAlchemy

    Mysql基础 一.安装 Windows: 1.下载 http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.31-winx64.zip 2.解压 ...

  10. python-day12 MySQL、sqlalchemy

    @第一节上周回顾没看 @博客day11 https://www.cnblogs.com/alex3714/articles/5950372.html @InnoDB,是MySQL的数据库引擎之一 @S ...

随机推荐

  1. Js/Jquery获取input file的文件名

    html代码:     <input type="file" name="file" id="file" class="in ...

  2. new Date(str)返回的时间结果在移动端比PC端快了8小时

    最近开发过程中,后端传过来一个“2018-03-15T17:53:19.6307928”字符串,需要将字符串转换成“2018-03-15  17:53”的格式展示出来.首先我使用了var time=n ...

  3. MYSQL 4种插入数据的方式比较

    4种插入数据的方式 第一种:insert into insert into是最常用的插入数据的方式,可以单条插入,也可以多条,还可以指定从其他表中select然后插入. 详细可以参考:insert语法 ...

  4. JFinal常量配置学习笔记

    在继承 JFinalConfig 类时,需要 实现 /** * Config constant */ public abstract void configConstant(Constants me) ...

  5. NopCommerce 3.80框架研究(二) MVC 表示层与数据验证

    表示层框架结构 /Views/Shared/_Root.Head.cshtml /Views/Shared/_Root.cshtml /Views/Shared/_ColumnsOne.cshtml ...

  6. eclipse Indigo搭建SSH框架详解

    SSH框架是最常用的框架之一,在搭建SSH框架的时候总有人遇到这样,那样的问题.下面我介绍一下SSH框架搭建的全过程. 第一步:准备工作.   下载好eclipse,Struts2,Spring,Hi ...

  7. Miller-Rabbin 素性测试 和 Pollard_rho整数分解

    今天学习一下Miller-Rabbin  素性测试 和 Pollard_rho整数分解. 两者都是概率算法. Miller_Rabbin素性测试是对简单伪素数pseudoprime测试的改进. (ps ...

  8. 索引属性 unique指定

    比较重要的属性有: 名字 db.collection.ensureIndex({},{name:''}) 在创建索引时,mongodb会自己给索引创建默认的名字,这种名字并不好记,我们看一下mongo ...

  9. 实现带查询功能的ComboBox控件

    实现效果: 知识运用: ComboBox控件的AutoCompleteMode属性 public AutoCompleteMode AutoCompleteMode{get;set;} //属性值为枚 ...

  10. 更换PostgreSql的data文件夹并重新服务器(此方法同样适用于系统崩溃后,找回数据的操作)

    *如果是系统崩溃,需要找回数据,PostgreSQL安装目录的data文件夹要存在 1.备份PostgreSQL安装目录到其他目录下 2.停止Postgres服务,可以在运行中输入services.m ...