1. # @ Time : 2021/1/31
    2. # @ Author : ecithy
    3. from sqlalchemy import create_engine, and_, or_
    4. from sqlalchemy.ext.declarative import declarative_base
    5. from sqlalchemy import Column, Integer, String, Float
    6. from sqlalchemy.orm import sessionmaker
    7. import random
    8. # localhost
    9. HOSTNAME = '127.0.0.1'
    10. DATABASE = 'demo'
    11. PORT = 3306
    12. USERNAME = 'root'
    13. PASSWORD = 'root'
    14. DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
    15. engine = create_engine(DB_URL)
    16. Base = declarative_base(engine)
    17. class Article(Base):
    18. __tablename__ = 'article2'
    19. id = Column(Integer, primary_key=True, autoincrement=True)
    20. title = Column(String(50))
    21. price = Column(Float, nullable=False)
    22. # def __repr__(self):
    23. def __str__(self):
    24. return "Article(title:{},price:{})".format(self.title, self.price)
    25. # Base.metadata.drop_all()
    26. Base.metadata.create_all()
    27. Session = sessionmaker(bind=engine)
    28. session = Session()
    29. # for i in range(6):
    30. # article = Article(title="title%s" % i, price=random.randint(1, 50))
    31. # session.add(article)
    32. # session.commit()
    33. # eq
    34. # result = session.query(Article).filter(Article.title == 'title0').all()
    35. # not eq mysql <>
    36. # result = session.query(Article).filter(Article.title != 'title0').all()
    37. # like 模糊查询 居 手机
    38. # title 包含 title xxxtitlexxx 2title
    39. # result = session.query(Article).filter(Article.title.like('%title%')).all()
    40. # print(result)
    41. # in Python关键字 _ 私有的
    42. # in [1, 4] 查询的是 id 为1,4 不是范围
    43. # result = session.query(Article).filter(Article.title.in_(['title0', 'title4'])).all()
    44. # not in
    45. # result = session.query(Article).filter(~Article.title.in_(['title1', 'title2'])).all()
    46. # result = session.query(Article).filter(Article.title.notin_(['title1', 'title2'])).all()
    47. # Null != 空
    48. # result = session.query(Article).filter(Article.title == None).all()
    49. # result = session.query(Article).filter(Article.title.is_(None)).all()
    50. # result = session.query(Article).filter(Article.title != None).all()
    51. # result = session.query(Article).filter(Article.title.isnot(None)).all()
    52. # and
    53. # result = session.query(Article).filter(Article.title == 'title0', Article.price == 48).all()
    54. # result = session.query(Article).filter(and_(Article.title == 'title0', Article.price == 48)).all()
    55. # result = session.query(Article).filter(Article.title == 'title0').filter(Article.price == 48).all()
    56. # print(result)
    57. # or 或者 满足一个条件就可以
    58. result = session.query(Article).filter(or_(Article.title == 'title0', Article.price == 17, Article.title == 'title2')).all()
    59. for data in result:
    60. print(data)
    61. # print(result)