直接上代码。代码里有注释。
# SQLAlchemy 是python编程语言下的一款ORM框架,该框架建立在
# 数据库API之上,使用关系对象映射进行数据库操作,简而言之:将对象
# 转换为SQL,然后使用数据API执行SQL并获取执行结果
# SQLALchemy中的数据类型与python的对应信息
# Text -> Long str
# Boolean -> bool
# BigInteger -> int
# Date -> Datetime.data
# DateTime -> Datatime.datetime
# Float -> float
# String -> str
from sqlalchemy import create_engine,MetaData,Table # 创建引擎
from sqlalchemy import Column,String,Integer,select
engine = create_engine(
"mysql+pymysql://root:s814466057@127.0.0.1:3306/test", #连接地址
max_overflow = 5, #最大连接数
pool_size=5, #连接池大小
echo=True #回显
)
metadata = MetaData()
#
user = Table(
'user',metadata, # 表名和元数据
Column('id',Integer,primary_key=True,autoincrement=True), # ID字段
Column('name',String(20)) # name字段
)
metadata.create_all(engine) # 创建表
# 原生语句的操作
# 插入数据
engine.execute("insert into user (name) values ('Echo')")
# # 更新数据
engine.execute("update user set id=5 where name='Echo'")
# 查询数据
result = engine.execute("select * from user")
for item in result:
print(item)
# # 删除数据
engine.execute("delete from user where id = 5")
# 表结构的操作
conn = engine.connect() #获取连接
# 执行插入
conn.execute(user.insert(),{'name':"python"})
# 修改数据
conn.execute(user.update().where(user.c.id==2).values(name='c++'))
# 查询数据,需要导入select函数
res = conn.execute((select([user.c.id,user.c.name])))
print(res.fetchall())
# 删除数据
conn.execute(user.delete().where(user.c.id==2))
conn.close()
# 集成ORM类操纵数据库
from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer
from sqlalchemy.orm import sessionmaker # 代替conn,执行数据库操作语句
from sqlalchemy.ext.declarative import declarative_base # 用于创建数据库表基类
engine = create_engine(
"mysql+pymysql://root:s814466057@127.0.0.1:3306/test", #连接地址
max_overflow = 5, #最大连接数
pool_size=5, #连接池大小
echo=True #回显
)
Base = declarative_base()
class Host(Base):
# 表名
__tablename__ = 'hosts',
# 字段
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=8080) # default 默认值
# 创建表
Base.metadata.create_all(engine)
if __name__ == '__main__':
Session = sessionmaker(bind=engine)
sess = Session()
h = Host(hostname='test1',ip_addr='127.0.0.1')
h2 = Host(hostname='test2', ip_addr='127.0.0.2',port=9001)
h3 = Host(hostname='test3', ip_addr='127.0.0.3', port=9003)
sess.add(h) # 添加一条数据
sess.add_all([h2,h3]) # 添加多条数据
# 查询Host表中id大于1的值,并删除
sess.query(Host).filter(Host.id >1).delete()
# 查询Host表中id=1的值,并修改
sess.query(Host).filter(Host.id == 1).update({'port':9000})
# 查询
res = sess.query(Host).filter_by(id=1).all()
for i in res:
print(i.hostname,i.port)
sess.commit() # 提交
# 集成ORM类操纵数据库
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship # 代替conn,执行数据库操作语句
from sqlalchemy.ext.declarative import declarative_base # 用于创建数据库表基类
engine = create_engine(
"mysql+pymysql://root:s814466057@127.0.0.1:3306/test", # 连接地址
max_overflow=5, # 最大连接数
pool_size=5, # 连接池大小
echo=True # 回显
)
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(125), nullable=True)
gender = Column(String(10), nullable=True, default="保密")
town = Column(String(125))
# 用于构建一对多的关系,一个用户会多种语言
# 关联的是Language类的名字,注意不能写成表的名字
# backref指通过什么名字来关联另一张表
language = relationship('Language', backref='user')
class Language(Base):
__tablename__ = 'language'
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(125), nullable=True)
advantage = Column(String(125), nullable=True)
disadvantage = Column(String(125), nullable=True)
# 构造外键
user_id = Column(Integer(), ForeignKey('user.id'))
# Base.metadata.create_all(engine)
if __name__ == '__main__':
Session = sessionmaker(engine)
session = Session()
# # 添加
# u1 = User(name='张三',gender='男',town='北京')
# u2 = User(name='李四',gender='女',town='河南')
# session.add_all([u1,u2])
# session.commit()
#
# l1 = Language(name='python',advantage='开发快',disadvantage='运行慢')
# # 建立关联,这里.user就是在backref中的user
# l1.user = u1
# session.add(l1)
# session.commit()
# u3 = User(name='王五',gender='女',town='天津')
# # 创建一对多关系
# u3.language = [
# Language(
# name='python3',
# advantage='开发快',
# disadvantage='运行慢'
# ),
# Language(
# name='C',
# advantage='运行极快',
# disadvantage='不好学'
# )
# ]
# session.add(u3)
# session.commit()
# 查询id为6的用户
u = session.query(User).filter_by(id=6).first()
print("用户:" + u.name + u.gender)
# 查询id为6的用户所关联的语言
lang = session.query(Language).filter_by(user_id=u.id)
for i in lang:
print("language:" + i.name)
# 删除用户
# u4 = User(name='马六',gender='男',town='云南')
# u4.language = [
# Language(
# name='python3.8',
# advantage='开发快',
# disadvantage='运行慢'
# ),
# Language(
# name='C#',
# advantage='运行极快',
# disadvantage='不好学'
# )
# ]
# session.add(u4)
# session.commit()
#u = session.query(User).filter(User.id == 8).first()
# 这里删除的只是用户,与之关联的语言并不会删除,关联数据空下的字段会变成null
# 在这里就是语言字段的ID会变成null,浪费空间
# 如果想要实现 级联删除数据。需要在user表中的relationship字段加上cascade
# language = relationship('Language', backref='user',cascade='all,delete')
# session.delete(u)
# session.commit()
# 更新
u = session.query(User).filter(User.id == 4).first()
u.name = '张便便'
session.commit()
# 集成ORM类操纵数据库
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship # 代替conn,执行数据库操作语句
from sqlalchemy.ext.declarative import declarative_base # 用于创建数据库表基类
engine = create_engine(
"mysql+pymysql://root:s814466057@127.0.0.1:3306/test", # 连接地址
max_overflow=5, # 最大连接数
pool_size=5, # 连接池大小
echo=True # 回显
)
Base = declarative_base()
# 多对多建表
class User2(Base):
__tablename__ = 'user2'
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(125), nullable=True)
gender = Column(String(10), nullable=True, default="保密")
town = Column(String(125))
language = relationship('Language2', back_populates='user2')
class Language2(Base):
__tablename__ = 'language2'
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(125), nullable=True)
advantage = Column(String(125), nullable=True)
disadvantage = Column(String(125), nullable=True)
user = relationship('User2', back_populates='language2')
# relationship函数是sqlalchemy对关系之间提供的一种便利的调用方式
# backref参数则对关系提供反向引用的声明
# 最新版本的sqlalchemy中对relationship引进了back_populate参数,和
# backref一样,不过需要两边定义,一般不常用,一般常用第三张表来保存关系
# 集成ORM类操纵数据库
from sqlalchemy import create_engine, ForeignKey, Table
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship # 代替conn,执行数据库操作语句
from sqlalchemy.ext.declarative import declarative_base # 用于创建数据库表基类
from sqlalchemy import or_,and_
engine = create_engine(
"mysql+pymysql://root:s814466057@127.0.0.1:3306/test", # 连接地址
max_overflow=5, # 最大连接数
pool_size=5, # 连接池大小
echo=True # 回显
)
Base = declarative_base()
User2Language = Table('user2_2_language2',Base.metadata,
Column('user2_id',ForeignKey('user2.id'),primary_key=True),
Column('language2_id',ForeignKey('language2.id'))
)
class User2(Base):
__tablename__ = 'user2'
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(125), nullable=True)
gender = Column(String(10), nullable=True, default="保密")
town = Column(String(125))
# secondary使用第三张表
language = relationship('Language2', backref='user2',cascade='all,delete',secondary=User2Language)
class Language2(Base):
__tablename__ = 'language2'
id = Column(Integer(), primary_key=True, autoincrement=True)
name = Column(String(125), nullable=True)
advantage = Column(String(125), nullable=True)
disadvantage = Column(String(125), nullable=True)
user_id = Column(Integer(), ForeignKey('user2.id'))
# Base.metadata.create_all(engine)
if __name__ == '__main__':
Session = sessionmaker(engine)
session = Session()
# 添加用户
# u1 = User2(name='张三',gender='男',town='北京')
# u2 = User2(name='李四', gender='女', town='北京')
# session.add_all([u1,u2])
# session.commit()
# # 添加语言
# ll = Language2(name='python',
# advantage='Hello',
# disadvantage='World'
# )
# ll.user2.append(u1)
# session.add(ll)
# session.commit()
# 同时添加
# u3 = User2(name='王五', gender='女', town='天津')
# u3.language = [
# Language2(
# name='Java',
# advantage='Hello',
# disadvantage='World'
# ),
# Language2(
# name='C#',
# advantage='Hello',
# disadvantage='World'
# ),
# ]
# session.add(u3)
# session.commit()
# 查找数据
# 查询有多少ID大于0的数据
count = session.query(User2).filter(User2.id > 0).count()
print(count)
# 查询所有的user,以userID降序排列, - 代表降序
li = session.query(User2).order_by(-User2.id).all()[:2]
o = session.query(User2).filter(or_(User2.id==1,User2.id==2)).all()
print(o)
a = session.query(User2).filter(and_(User2.id==1,User2.id==2)).all()
print(a)
l = session.query(User2).filter(User2.name.like('_三')).all()
print(l)