src/db/modls.py
# -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,String,Integer from sqlalchemy import create_engine Basic=declarative_base() class Index_shop_info(Basic): __tablename__ = "Index_shop_info" id = Column('id', Integer, primary_key = True) title = Column(String(50)) link = Column(String(1024)) sl_baozheng= Column(String(50)) __table_args__ = { 'mysql_charset': 'utf8' } class Shop_detail(Basic): __tablename__ = "Shop_detail" id = Column('id', Integer, primary_key=True) __table_args__ ={ 'mysql_charset': 'utf8' } engine = create_engine('mysql+mysqlconnector://root:root@127.0.0.1/xianyu', convert_unicode=True) metadata = Basic.metadata.create_all(bind=engine)
orm
from src.db import models from sqlalchemy.orm import sessionmaker from contextlib import closing def get_session(): session=sessionmaker(bind=models.engine)() return session def query_all(session,table=None): with closing(session) as session: reuslt = session.query(table).all() return reuslt def add_object(session,rowobject): with closing(session) as session : result=session.add_all(rowobject) session.commit() return result def myfilter(session=None,tableclass=None,**kwargs): query_list=tableclass #{"字段":值} tiaojian_dic={getattr(tableclass,k):v for k,v in kwargs.items() } tiaojian_list=[k==v for k,v in tiaojian_dic.items()] for k,v in tiaojian_dic.items() : tiaojian_list.append(k==v) query_list=session.query(tableclass).filter(*tiaojian_list) return query_list if __name__ == '__main__': session=get_session() #查所有 query_all(session,models.Index_shop_info) #过滤 result=myfilter(session=session,tableclass=models.Index_shop_info,sl_baozheng = '实力保证', id = 1) #增 row_list=[models.Index_shop_info(title="test",link='test',sl_baozheng='test')] add_object(session,row_list)