sqlalchemy
1. touch model.py
from sqlalchemy import Column, String, Integer, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///./test.db') Base = declarative_base() class Corp(Base): __tablename__ = 'corp' # 企业 id = Column(Integer, primary_key=False, autoincrement=True) name = Column(String(100), nullable=False, primary_key=True) # 公司名称 href = Column(String(100), nullable=True) # 网站地址 belong = Column(String(100), nullable=True) # 所属网站 author = Column(String(10), nullable=True) # 采集作者 flag = Column(String(100), nullable=True) # 采集标志位 # 定义初始化数据库函数 def init_db(): Base.metadata.create_all(engine) filename = './zl.txt' with open(filename, 'r') as f: company = f.readlines() companys = [i.strip() for i in company if len(i.strip())>5] engine.execute(Corp.__table__.insert(), [dict(name=i) for i in companys]) # 删除数据库函数 def drop_db(): Base.metadata.drop_all(engine) # drop_db() # init_db() Session = sessionmaker(bind=engine) session = Session()
2. touch sql.py
import sys sys.path.append('/home/yugengde/code/byb/risk/usr/corpinfo') from model import session, Corp # 1. insert # engine.execute(Corp.__table__.insert(), [dict(name=i) for i in companys]) # 2. query print('*'*100) # companys = session.query(Corp).filter(Corp.name=='深圳市福特电子有限 公司') # print(companys) companys = session.query(Corp).filter() print([company.name for company in companys])