Python 使用ORM框架 SQLAlchemy

官网 

https://www.sqlalchemy.org/download.html

SQLALCHEMY用法详解  https://blog.csdn.net/kepengs/article/details/82582338

Python 使用ORM框架  https://blog.csdn.net/hhy1107786871/article/details/87905421

python之ORM操作  https://www.cnblogs.com/zhangyux/p/6284669.html

SQLAlchemy 字段、要点 https://blog.csdn.net/Could_tzw/article/details/116979816

config.yaml

DB_Str: 'mysql+pymysql://root:haosql@localhost:3306/test1'

 

config.py

import yaml,os,sys

if 'python' in sys.executable:
    abs_path = lambda file: os.path.abspath(os.path.join(os.path.dirname(__file__), file))
else:
    abs_path = lambda file: os.path.abspath(os.path.join(os.path.dirname(sys.executable), file))  # mac 上打包后 __file__ 指定的是用户根路径,非当执行文件路径

config = yaml.full_load(open(abs_path('../config.yaml'), encoding='utf8'))


if __name__ == '__main__':
    print(config['mysql']['ip'])
View Code

main.py

# 导入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from utils.log    import Logger
from utils.config import config
 
# 创建对象的基类:
Base = declarative_base()
 
# 定义User对象:
class User(Base):
    # 表的名字:
    __tablename__ = 'user'
 
    # 表的结构:
    id = Column(String(20), primary_key=True)
    name = Column(String(20))
 
# 初始化数据库连接:
engine = create_engine(config.get('DB_Str'))
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)

Base.metadata.create_all(engine)

# 创建session对象:
session = DBSession()
# 创建新User对象:
new_user = User(id='5', name='Bob')
# 添加到session:
session.add(new_user)
# 提交即保存到数据库:
session.commit()
# 关闭session:
session.close()
View Code

 

posted @ 2022-10-24 13:58  simadi  阅读(42)  评论(0编辑  收藏  举报