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"
相关推荐
网络风云30 分钟前
golang中的包管理-下--详解
开发语言·后端·golang
小唐C++1 小时前
C++小病毒-1.0勒索
开发语言·c++·vscode·python·算法·c#·编辑器
S-X-S1 小时前
集成Sleuth实现链路追踪
java·开发语言·链路追踪
北 染 星 辰1 小时前
Python网络自动化运维---用户交互模块
开发语言·python·自动化
codists1 小时前
《CPython Internals》阅读笔记:p336-p352
python
佳心饼干-1 小时前
数据结构-栈
开发语言·数据结构
我们的五年1 小时前
【C语言学习】:C语言补充:转义字符,<<,>>操作符,IDE
c语言·开发语言·后端·学习
灯火不休ᝰ2 小时前
[java] java基础-字符串篇
java·开发语言·string
Мартин.2 小时前
[Meachines] [Easy] GoodGames SQLI+Flask SSTI+Docker逃逸权限提升
python·docker·flask
励志去大厂的菜鸟2 小时前
系统相关类——java.lang.Math (三)(案例详细拆解小白友好)
java·服务器·开发语言·深度学习·学习方法