:sqlalchemy操作
Posted haojunliancheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了:sqlalchemy操作相关的知识,希望对你有一定的参考价值。
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
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
### 连接mysql
engine = create_engine("mysql+pymysql://root:[email protected]:3306/db3?charset=utf8", max_overflow=5)
engine = create_engine("mysql+pymysql://root:[email protected]:3306/db3?charset=utf8", max_overflow=5)
Base = declarative_base()
‘‘‘
create table users(
id int auto_increment primary key,
name varchar(32) not null default ‘‘,
extra varchar(32) not null default ‘‘
)
‘‘‘
‘‘‘
Usertype
id title xxoo
1 普通用户
row.xxoo : 多条记录对象
‘‘‘
class UserType(Base):
__tablename__ = ‘usertype‘ ### 表名
id = Column(Integer, autoincrement=True, primary_key=True)
title = Column(String(32), nullable=False, server_default=‘‘)
Usertype
id title xxoo
1 普通用户
row.xxoo : 多条记录对象
‘‘‘
class UserType(Base):
__tablename__ = ‘usertype‘ ### 表名
id = Column(Integer, autoincrement=True, primary_key=True)
title = Column(String(32), nullable=False, server_default=‘‘)
‘‘‘
users
id name extra type_id
1 zekai nb 1
usertype = releationship(‘Usertype‘)
row.usertype
‘‘‘
class Users(Base):
__tablename__ = ‘users‘
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String(32), nullable=False, server_default=‘‘)
extra = Column(String(32), nullable=False, server_default=‘‘)
type_id = Column(Integer, ForeignKey(UserType.id))
usertype = relationship(‘UserType‘, backref=‘xxoo‘)
users
id name extra type_id
1 zekai nb 1
usertype = releationship(‘Usertype‘)
row.usertype
‘‘‘
class Users(Base):
__tablename__ = ‘users‘
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String(32), nullable=False, server_default=‘‘)
extra = Column(String(32), nullable=False, server_default=‘‘)
type_id = Column(Integer, ForeignKey(UserType.id))
usertype = relationship(‘UserType‘, backref=‘xxoo‘)
__table_args__ = (
# UniqueConstraint(‘id‘, ‘name‘, name=‘uix_id_name‘), ### 联合唯一索引
# Index(‘ix_name_extra‘, ‘name‘, ‘extra‘), ### 组合索引
)
# UniqueConstraint(‘id‘, ‘name‘, name=‘uix_id_name‘), ### 联合唯一索引
# Index(‘ix_name_extra‘, ‘name‘, ‘extra‘), ### 组合索引
)
def drop_db():
Base.metadata.drop_all(engine)
def create_db():
## 会将当前执行文件中所有继承自Base类的类,生成表
Base.metadata.create_all(engine)
# drop_db()
create_db()
###操作表中的数据
Session = sessionmaker(bind=engine)
session = Session()
session = Session()
### 增加一条数据
# obj = UserType(title=‘普通用户‘)
# session.add(obj)
### 添加多条数据
# session.add_all([
# UserType(title=‘VIP用户‘),
# UserType(title=‘VIP中P用户‘),
# UserType(title=‘SVIP用户‘),
# UserType(title=‘黑金用户‘)
# ])
# session.add_all([
# UserType(title=‘VIP用户‘),
# UserType(title=‘VIP中P用户‘),
# UserType(title=‘SVIP用户‘),
# UserType(title=‘黑金用户‘)
# ])
### 查询
# ### 查询全部 返回的是一个列表, 列表中套对象
# res = session.query(UserType).all()
# for row in res:
# print(row.id, row.name)
# ### 查询全部 返回的是一个列表, 列表中套对象
# res = session.query(UserType).all()
# for row in res:
# print(row.id, row.name)
# ### 查询一条数据
# res = session.query(UserType).first()
# print(res)
# res = session.query(UserType).first()
# print(res)
### where条件
# res = session.query(UserType).filter(UserType.name==‘VIP用户‘, UserType.id==2).all()
# for row in res:
# print(row.id, row.name)
# print(res[0].name, res[0].id)
# res = session.query(UserType).filter_by(name=‘VIP用户‘).all()
# print(res)
# res = session.query(UserType).filter(UserType.name==‘VIP用户‘, UserType.id==2).all()
# for row in res:
# print(row.id, row.name)
# print(res[0].name, res[0].id)
# res = session.query(UserType).filter_by(name=‘VIP用户‘).all()
# print(res)
### 删除:
# session.query(UserType).filter(UserType.id>3).delete()
# session.query(UserType).filter(UserType.id>3).delete()
## 修改
# session.query(UserType).filter(UserType.id == 3).update("name" : "SVIP用户")
# session.query(UserType).filter(UserType.id == 3).update("name" : "SVIP用户")
### MySQL 高级查询操作
#### 通配符 分组 分页 排序 between and in not in
### between ... and ...
# res = session.query(UserType).filter(UserType.id.between(1,3)).all()
# for row in res:
# print(row.id, row.title)
# res = session.query(UserType).filter(UserType.id.between(1,3)).all()
# for row in res:
# print(row.id, row.title)
### in 操作 bool_
# res = session.query(UserType).filter(UserType.id.in_([1,3,4])).all()
# print(res)
# res = session.query(UserType).filter(UserType.id.in_([1,3,4])).all()
# print(res)
### not in
# select * from Usertype
# res = session.query(UserType).filter(~UserType.id.in_([1,3,4])).all()
# for row in res:
# print(row.id, row.title)
#
# session.query(UserType).filter(Users.id.in_(session.query(Users.id).filter_by(name=‘eric‘))).all()
# res = session.query(UserType.title).filter(~UserType.id.in_([1,3,4])).all()
# for row in res:
# print( row.title)
# select * from Usertype
# res = session.query(UserType).filter(~UserType.id.in_([1,3,4])).all()
# for row in res:
# print(row.id, row.title)
#
# session.query(UserType).filter(Users.id.in_(session.query(Users.id).filter_by(name=‘eric‘))).all()
# res = session.query(UserType.title).filter(~UserType.id.in_([1,3,4])).all()
# for row in res:
# print( row.title)
from sqlalchemy import and_, or_
### 通配符
# ret = session.query(UserType).all()
### 通配符
# ret = session.query(UserType).all()
from sqlalchemy.sql import func
# res = session.query(
# Users.type_id,
# func.max(Users.id),
# func.min(Users.id)).group_by(Users.type_id).all()
#
# print(res)
ret = session.query(
func.max(Users.id),
func.min(Users.id)).group_by(Users.type_id).having(func.min(Users.id) >2).all()
# res = session.query(
# Users.type_id,
# func.max(Users.id),
# func.min(Users.id)).group_by(Users.type_id).all()
#
# print(res)
ret = session.query(
func.max(Users.id),
func.min(Users.id)).group_by(Users.type_id).having(func.min(Users.id) >2).all()
### left join
###1. 查询某一个用户的用户类型
### 第一种方法:
# res = session.query(Users,UserType).join(UserType, isouter=True).all()
# # print(res)
# for row in res:
# print(row[0].id, row[0].name, row[1].title)
### 第二种方法
# res = session.query(Users).all()
# for row in res:
# print(row.id, row.name, row.extra, row.usertype.title)
# res = session.query(Users).all()
# for row in res:
# print(row.id, row.name, row.extra, row.usertype.title)
### 2. 某一个类型下面的用户
### 第一种方法
# res = session.query(UserType).all()
# for row in res:
# print(row.id, row.title, session.query(Users).filter(Users.type_id == row.id).all() )
### 第一种方法
# res = session.query(UserType).all()
# for row in res:
# print(row.id, row.title, session.query(Users).filter(Users.type_id == row.id).all() )
### 第二种方法
# res = session.query(UserType).all()
#
# for row in res:
# print(row.id, row.title, row.xxoo)
# res = session.query(UserType).all()
#
# for row in res:
# print(row.id, row.title, row.xxoo)
-
1.查看数据库编码格式
-
-
mysql> show variables like ‘character_set_database‘;
-
-
-
2.查看数据表的编码格式
-
-
mysql> show create table <表名>;
-
-
-
3.创建数据库时指定数据库的字符集
-
-
mysql>create database <数据库名> character set utf8;
-
4.创建数据表时指定数据表的编码格式
-
-
create table tb_books (
-
name varchar(45) not null,
-
price double not null,
-
bookCount int not null,
-
author varchar(45) not null ) default charset = utf8;
-
5.修改数据库的编码格式
-
-
mysql>alter database <数据库名> character set utf8;
-
6.修改数据表格编码格式
-
-
mysql>alter table <表名> character set utf8;
-
7.修改字段编码格式
-
-
mysql>alter table <表名> change <字段名> <字段名> <类型> character set utf8;
-
-
mysql>alter table user change username username varchar(20) character set utf8 not null;
-
8.添加外键
-
-
mysql>alter table tb_product add constraint fk_1 foreign key(factoryid) references tb_factory(factoryid);
-
mysql>alter table <表名> add constraint <外键名> foreign key<字段名> REFERENCES <外表表名><字段名>;
-
9.删除外键
-
-
mysql>alter table tb_people drop foreign key fk_1;
-
mysql>alter table <表名> drop foreign key <外键名>;
以上是关于:sqlalchemy操作的主要内容,如果未能解决你的问题,请参考以下文章