Python sqlalchemy使用

基本结构

#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC
@file: base_db.py
@time: 2023/6/19 21:34
@desc:
"""
from sqlalchemy import create_engine,text
from sqlalchemy.orm import sessionmaker,scoped_session
from contextlib import contextmanager
from sqlalchemy.pool import QueuePool
from sdk.base.base_tables import Base

class DB(object):
    """

    """
    def __init__(self,username,password,host,port,db,poll_size=50,debug=True):
        self.username = username
        self.password = password
        self.host = host
        self.port = port
        self.db = db
        self.poll_size = poll_size
        # 初始化数据库连接池:
        self.engine = create_engine(f'mysql+mysqlconnector'
                                    f'://{self.username}:{self.password}'
                                    f'@{self.host}:{self.port}/{self.db}',
                                    poolclass=QueuePool,pool_size=self.poll_size,echo=True if debug else False)
        self.__create_db()
        # 创建线程安全的DBSession类型:
        self.db_session = scoped_session(sessionmaker(bind=self.engine, autocommit=False))

    def __create_db(self):
        """
        新建表
        :return:
        """
        Base.metadata.create_all(self.engine, checkfirst=True)
    def run_origin_sql(self,session,sql):
        """
        执行原生sql
        :param session:
        :param sql:
        :return:
        """
        return session.execute(text(f"""{sql}"""))

    @contextmanager
    def get_session(self):
        """
        返回数据库连接对象
        :return:
        """
        session = self.db_session()
        try:
            yield session
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

base_tables.py

# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: base_tables.py
@time: 2023/12/9 21:57
@desc: 

"""
from sqlalchemy.ext.declarative import declarative_base


# 创建对象的基类,单写出来,避免循环引用
Base = declarative_base()

使用样例

from sdk.base.base_db import *
from db_tables.KDQ_USER_INFO import *
from db_tables.KDQ_CONTENT_INFO import *
from db_tables.KDQ_COMMENT_INFO import *
from test1 import *
import time

db = DB(host="127.0.0.1", port=3306, username="root", password="123456", db=DB_KDQ)
with db.get_session() as session:
	session.***

from db_tables.KDQ_USER_INFO import *

from db_tables.KDQ_CONTENT_INFO import *

from db_tables.KDQ_COMMENT_INFO import *

这三个是写的数据表表类

差不多长这样

# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: KDQ_USER_INFO.py
@time: 2023/12/9 21:54
@desc: 

"""
from sqlalchemy.sql import func
from sqlalchemy import Column,INT,VARCHAR,TEXT,Boolean,DateTime
from sdk.base.base_tables import Base

class UserInfo(Base):
    """
    用户信息表
    """

    __tablename__ = 'user_info'
    id = Column(INT,primary_key=True,autoincrement=True,nullable=False,index=True,unique=True)
    user_id = Column(INT,nullable=False,unique=True)
    user_name = Column(VARCHAR(50),nullable=False)
    nick_name = Column(VARCHAR(255),nullable=False)
    real_user_info = Column(VARCHAR(255),nullable=False)
    avatar = Column(TEXT,nullable=True)
    role_set = Column(TEXT,nullable=True)
    permission_set = Column(TEXT,nullable=True)
    email = Column(VARCHAR(100),nullable=False,default=0)
    mobile = Column(VARCHAR(11),nullable=False,default=0)
    gender = Column(VARCHAR(10),nullable=False)
    use_default_password = Column(Boolean,nullable=True,default=False)
    comment_num = Column(INT,nullable=False,default=0)
    like_num = Column(INT,nullable=False,default=0)
    view_num = Column(INT,nullable=False,default=0)
    follower_num = Column(INT,nullable=False,default=0)
    mute_num = Column(INT,nullable=False,default=0)
    create_time = Column(DateTime,nullable=False,default=func.now())
    update_time = Column(DateTime,nullable=False,default=func.now(),onupdate=func.now())
    __table_args__ = {
        'mysql_charset': 'utf8mb4'  # 设置字符集为utf8mb4
    }


DB_KDQ = "demo"
相关推荐
PieroPc13 分钟前
Python 写的 智慧记 进销存 辅助 程序 导入导出 excel 可打印
开发语言·python·excel
2401_857439693 小时前
SSM 架构下 Vue 电脑测评系统:为电脑性能评估赋能
开发语言·php
SoraLuna3 小时前
「Mac畅玩鸿蒙与硬件47」UI互动应用篇24 - 虚拟音乐控制台
开发语言·macos·ui·华为·harmonyos
xlsw_3 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
梧桐树04294 小时前
python常用内建模块:collections
python
Dream_Snowar4 小时前
速通Python 第三节
开发语言·python
高山我梦口香糖5 小时前
[react]searchParams转普通对象
开发语言·前端·javascript
信号处理学渣6 小时前
matlab画图,选择性显示legend标签
开发语言·matlab
红龙创客6 小时前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
蓝天星空6 小时前
Python调用open ai接口
人工智能·python