from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 创建数据库连接
engine = create_engine('sqlite:///configurations.db')
Base = declarative_base()
# 定义 ORM 模型
class Configuration(Base):
__tablename__ = 'configurations'
id = Column(Integer, primary_key=True)
key_name = Column(String(255), unique=True)
value = Column(Text)
# 创建表(如果不存在)
Base.metadata.create_all(engine)
# 使用会话进行数据操作
Session = sessionmaker(bind=engine)
session = Session()
# 读取配置项
def get_configuration(key):
config = session.query(Configuration).filter_by(key_name=key).first()
return config.value if config else None
# 更新配置项
def update_configuration(key, value):
config = session.query(Configuration).filter_by(key_name=key).first()
if config:
config.value = value
else:
new_config = Configuration(key_name=key, value=value)
session.add(new_config)
session.commit()
# 示例使用
update_configuration('logging_level', 'info') # 更新配置项
print(get_configuration('logging_level')) # 读取配置项
数据驱动编程 使用 sqlite sqlalchemy
最新推荐文章于 2024-06-10 13:08:00 发布