python sqlalchemy

得意时要看淡,失意时要看开。不论得意失意,切莫大意;不论成功失败,切莫止步。志得意满时,需要的是淡然,给自己留一条退路;失意落魄时,需要的是泰然,给自己觅一条出路python sqlalchemy,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!