zoukankan      html  css  js  c++  java
  • sqlAlchemy搭建sqliteOrm

    一:引入文件

    from sqlalchemy import Column, Integer, VARCHAR, Text
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    Base = declarative_base() #构造基类

    二:表结构

    class TiKu(Base):
        __tablename__ = 'spider_tiku'
        id = Column(Integer(), primary_key=True, autoincrement=True)
        kaoshi = Column(VARCHAR(200), nullable=True)
        subject = Column(VARCHAR(200), nullable=True)
        chapter = Column(VARCHAR(200), nullable=True)
        section = Column(VARCHAR(200), nullable=True)
        tixing = Column(VARCHAR(20), nullable=True)
        question_case = Column(Text(), nullable=True)
        question = Column(Text, nullable=True)
        a = Column(VARCHAR(1000), nullable=True)
        b = Column(VARCHAR(1000), nullable=True)
        c = Column(VARCHAR(1000), nullable=True)
        d = Column(VARCHAR(1000), nullable=True)
        e = Column(VARCHAR(1000), nullable=True)
        other_sections = Column(VARCHAR(3000), nullable=True)
        answer = Column(VARCHAR(500), nullable=True)
        analysis = Column(Text(), nullable=True)
        source = Column(Text(), nullable=True)
    
        def __str__(self):
            return '< {} {} {}>'.format(self.kaoshi, self.subject, self.chapter)

    三:sqlite orm

    class SqliteOrm(object):
    
        def __init__(self, path):
            sqlite_path = 'sqlite:///{}'.format(path)
            self.engine = create_engine(sqlite_path)
            Session = sessionmaker(bind=self.engine)
            self.session = Session()
    
        def create_table(self):
            self.drop_table()
            Base.metadata.create_all(self.engine)
    
        def insert(self, obj):
            # 将该实例插入到表
            self.session.add(obj)
            self.session.commit()
    
        def insert_many(self, batch_data: list):
            # 一次插入多条记录形式
            self.session.add_all(batch_data)
            self.session.commit()
    
        def drop_table(self, table_name='spider_tiku'):
            try:
                self.execute_sql('drop table %s' % table_name)
            except Exception as e:
                pass
    
        def execute_sql(self, sql):
            self.session.execute(sql)
  • 相关阅读:
    1.ok6410移植bootloader,移植u-boot,学习u-boot命令
    ok6410按键中断编程,linux按键裸机
    四. jenkins部署springboot项目(1)--window环境
    一.jenkins安装(windows环境)
    oracle服务端导出/导入方式expdp/impdp
    linux 日志文件查看
    linux kafka进程挂了 自动重启
    kafka manager遇到的一些问题
    if条件语句
    shell脚本的条件测试与比较
  • 原文地址:https://www.cnblogs.com/li1992/p/11307504.html
Copyright © 2011-2022 走看看