python sqlalchemy 框架操作mysql数据库
# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: JHC
@license: None
@contact: JHC000abc@gmail.com
@file: sqlalchemy_test.py
@time: 2022/09/11/ 23:56
@desc:
"""
import enum
from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean, Date, DateTime, Enum, Text, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime
HOSTNAME = "localhost"
PORT = "3306"
DATABASE = "test_db"
USERNAME = "root"
PASSWORD = "123456"
DB_URI = "mysql+pymysql://{}:{}@{}:{}/{}".format(
USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE
)
engine = create_engine(DB_URI)
Base = declarative_base(engine)
session = sessionmaker(engine)()
# with engine.connect() as con:
# res = con.execute('select * from test_table;')
# for i in res.fetchall():
# print(i)
class TagEnum(enum.Enum):
"""
枚举
"""
python = "PYTHON"
flask = "FLASK"
django = "DJANGO"
class News(Base):
__tablename__ = "user_table"
id = Column(Integer,primary_key=True,autoincrement=True)
username = Column(String(20))
passwd = Column(String(20))
sex = Column(Boolean,default=True)
address = Column(String(255))
skill = Column(Enum(TagEnum))
desc = Column(Text)
date = Column(Date,default=datetime.datetime.now())
create_time = Column(DateTime,default=datetime.datetime.strptime("1999-12-31 00:00:00","%Y-%m-%d %H:%M:%S"))
# 映射数据表
# Base.metadata.drop_all()
# Base.metadata.create_all()
# 添加数据
p = News(username="zhangsa",passwd="123456",address="唐山法院",desc="傻逼1号")
session.add(p)
session.commit()
result = session.query(News.id,News.sex).all()
print(result)
avg = session.query(func.avg(News.id)).first()
print(avg[0])
count = session.query(func.count(News.id)).first()
print(count[0])
max = session.query(func.max(News.id)).first()
print(max[0])
min = session.query(func.min(News.id)).first()
print(min[0])
sum = session.query(func.sum(News.id)).first()
print(sum[0])
all_data = session.query(News).limit(2).all()
print("all_data",all_data)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/156896.html