注:针对的是查询出来的是单条对象
1.config.py文件
#!/usr/bin/env python #-*- coding: utf-8 -*- from sqlalchemy import create_engine,Column,String,Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker HOSTNAME = ‘127.0.0.1‘ PORT = ‘3306‘ DATABASE = ‘1‘ USERNAME = ‘root‘ PASSWORD = ‘root‘ DB_URI = "mysql+mysqlconnector://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) session = sessionmaker(engine)() class Views(Base): __tablename__ = ‘views‘ id = Column(Integer, primary_key=True) name = Column(String(100)) ports = Column(String(100)) def to_dict(self): model_dict = dict(self.__dict__) del model_dict[‘_sa_instance_state‘] return model_dict Base.to_dict = to_dict 2.mian.py文件..........
Info = session.query(Views).filter_by(id=1).first()Info.to_dict() # 把查询得到的结果转换成字典样式,键是数据表中的字段名,值是数据表中对应的值
..........
原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/10219961.html
时间: 2024-10-10 17:31:30