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 @   simadi  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2013-10-24 百度音乐助手 下载高品质音乐
2013-10-24 FileZilla 错误425 Can't open data connection 读取目录列表失败
点击右上角即可分享
微信分享提示