python 使用sqlalchemy 操作数据库

初始化连接数据库 (使用之前请先安装sqlalchemy、pymysql包),创建一个exts目录,创建__init__.py文件,内容如下

安装SQLAlchemy包 pip install SQLAlchemy
安装pymysql包 pip install pymysql
from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy.orm import Session


class Database(object):
    def __init__(self, username, password, host, port, database):
        self.username = username
        self.password = password
        self.host = host
        self.port = port
        self.database = database
        self.database_connection = (
            "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8&autocommit=true".format(
                self.username, self.password, self.host, self.port, self.database
            )
        )
        self.engine = create_engine(self.database_connection, pool_pre_ping=True, pool_recycle=180)
        self.session = Session(self.engine)
        self.metadata = MetaData()

    def tables(self, table):
        return Table(table, self.metadata, autoload=True, autoload_with=self.engine)

    def commit(self):
        return self.session.commit()

# 连接数据库信息
def content_db(dbs):
    database = Database(
        username="",
        password="",
        host="",
        port="",
        database=dbs,
    )
    return database

测试调用

from exts import content_db

# 连接数据库
dbname = content_db("dbname")

# 连接表
tablename = dbname.tables("tablename")

# 示例查询语句
dbname.session.query(tablename).filter_by(user_id=user_id, status=1).first()
posted @ 2022-07-08 09:57  昌慶  阅读(330)  评论(0编辑  收藏  举报