又是好久好久好久过去了

最近学了一点点Flask基础,以及数据库的ORM操作,再就是复习了一下前面学的

进阶课要结束啦,马上要开始学习爬虫了

加油~

留一个备份

SQLAlchemy_DB.py

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from faker import Faker
import random

engine = create_engine('sqlite:///TEST.db')
Base = declarative_base(engine)
fake = Faker('zh-cn')


class User(Base):
    __tablename__ = 'uesr'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(64), unique=True, nullable=False, index=True)
    age = Column(Integer, nullable=False)

    def __repr__(self):
        return '<User|name:{},age:{}>'.format(self.name, self.age)


def add_faker_data():
    for i in range(30):
        sql = User(name=fake.name(), age=random.randint(14, 24))
        try:
            session.add(sql)
            session.commit()
        except:
            session.rollback()


if __name__ == '__main__':
    session = sessionmaker(engine)()
    Base.metadata.create_all()
    print('welcome,inti faker data')
    add_faker_data()
    print('Bye')

SQLAlchemy_main.py

# 第一次运行时请先运行db.py 初始化数据库

from db import Base, engine, User, sessionmaker
import sys


class ClassData:
    def __init__(self):
        self.session = sessionmaker(engine)()

    def sql_add(self, **kwargs):
        sql = User(**kwargs)
        try:
            self.session.add(sql)
            self.session.commit()
        except:
            print("[WARING]出现异常。回滚操作:{}".format(sql))
            self.session.rollback()
        finally:
            print("[SQL]写入{}语句执行完毕。".format(kwargs))

    def sql_adds(self, *args):
        for i in args:
            sql = User(name=i[0], age=i[1])
            try:
                self.session.add(sql)
                self.session.commit()
            except:
                print("[WARING]出现异常。撤回操作:{}".format(sql))
                self.session.rollback()
            finally:
                print("[SQL]写入{}语句执行完毕。".format(i))

    def sql_del(self, **kwargs):
        print('[SQL]正在删除:{}号记录。'.format(kwargs['id']))
        try:
            self.session.query(User).filter_by(**kwargs).delete()
            self.session.commit()
        except:
            self.session.rollback()
        finally:
            print("[SQL]语句执行完毕。")

    def sql_re(self, *args, **kwargs):
        print('[SQL]正在修改{}的数据。'.format(args))
        try:
            self.session.query(User).filter_by(name=args[0]).update(kwargs)
            self.session.commit()
            print('[SQL]{}>>>{}√'.format(args, kwargs))
        except:
            self.session.rollback()
            print('[WARING]语句执行失败,撤回修改{}。'.format(kwargs))
        finally:
            print("[SQL]语句执行完毕。")


if __name__ == '__main__':
    classdata = ClassData()
    classdata.sql_add(name='小红', age='17')
    classdata.sql_add(name='小红', age='17')
    classdata.sql_adds(("rianley", 18), ("Egon", 20), ("wanghui", 21))
    classdata.sql_del(id=4)
    classdata.sql_re('小红', age=18)
    classdata.session.close()
    sys.exit(0)