赞
踩
pip install sqlalchemy;
# 导入引擎模块from sqlalchemy import create_engine# 导入基类模块from sqlalchemy.ext.declarative import declarative_base# 导入字段类from sqlalchemy import Column, Integer, String# 导入会话模块from sqlalchemy.orm import sessionmaker# 实体类的基类Base = declarative_base()# 实体类class Teacher(Base): ''' 实体类的创建有两个方面的用处: 1:如果数据库中没有表,那么可以使用实体类创建 2:如果数据库中有表,实体类可以映射表的结构,对表的CRUD操作 ''' # 表名必须指定 __tablename__ = 'teacher' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(255)) age = Column(Integer) # 打印实例的使用可以发现,数据也是保存在实体类实例的__dict__中 def __repr__(self): # print(self.__dict__) return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age) __str__ = __repr__# 创建连接引擎host = 'localhost'port = 3306username = 'zengzeng'password = '123456'db = 'XKD_Python_Course'connect_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)engine = create_engine(connect_str, echo=True)# 创建表Base.metadata.create_all(engine)# 删除表# Base.metadata.drop_all(engine)
我们现在命令工具中查看一下数据库中有没有我们想要的teacher表,上一篇文章中讲过,先登录mysql:mysql -uzengzeng -p123456,然后进入我们要使用的数据库:use XKD_Python_Course,我们先通过:show tables;查看一下数据库中的表,发现没有teacher表
那现在就可以执行代码,创建数据库了,创建好后我们可以在命令行查看一下:show tables;,发现teacher表已经存在了,创建表成功yes!
想要删除刚刚创建的表,可以使用drop_all()方法,执行代码,再查看数据库表,就可以看teacher表已经被删除了
Base.metadata.drop_all(engine)
from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Stringfrom sqlalchemy.orm import sessionmakerBase = declarative_base()class Teacher(Base): __tablename__ = 'teacher' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(255)) age = Column(Integer) def __repr__(self): # print(self.__dict__) return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age) __str__ = __repr__host = 'localhost'port = 3306username = 'zengzeng'password = '123456'db = 'XKD_Python_Course'connect_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)engine = create_engine(connect_str, echo=True)# 创建会话,用于提交数据Session = sessionmaker(bind=engine)session = Session()# 创建多行行实例,给表添加数据try: lst = [] for i in range(10): teacher = Teacher() teacher.name = 'zengzeng' + str(i) teacher.age = 20 + i lst.append(teacher) print(teacher) # session.add(student) 可以添加一行记录,也可以添加多行记录 # 注意:这里将行记录实例添加到session,不会提交,需要手动提交 session.add_all(lst)except Exception as e: print('~~~~~~~~~~~'*200) session.rollback() print(e)finally: session.commit()
我们执行代码,然后去命令工具查看一下表是否插入数据:select * from teacher;
from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Stringfrom sqlalchemy.orm import sessionmakerBase = declarative_base()class Teacher(Base): __tablename__ = 'teacher' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(255)) age = Column(Integer) def __repr__(self): # print(self.__dict__) return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age) __str__ = __repr__host = 'localhost'port = 3306username = 'zengzeng'password = '123456'db = 'XKD_Python_Course'conn_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)engine = create_engine(conn_str, echo=False)Session = sessionmaker(bind=engine)session = Session()teacher_obj = session.query(Teacher)for teacher in teacher_obj: print(teacher) # 返回结果:{'_sa_instance_state': , 'age': 20, 'name': 'nihao0', 'id': 1}print('*'*300)# 直接返回实例对象teacher = session.query(Teacher).get(4)print(teacher) # 返回结果:{'_sa_instance_state': , 'age': 23, 'name': 'nihao3', 'id': 4}print(teacher.id) # 返回 aobamaprint(teacher.name)print(teacher.age)print('*'*300)# 返回的是可迭代对象teacher_results = session.query(Teacher).filter(Teacher.id == 5)for teacher in teacher_results: # 拿到student实例对象 print(teacher)
from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Stringfrom sqlalchemy.orm import sessionmakerBase = declarative_base()class Teacher(Base): __tablename__ = 'teacher' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(255)) age = Column(Integer) def __repr__(self): # print(self.__dict__) return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age) __str__ = __repr__# 创建连接引擎host = 'localhost'port = 3306username = 'zengzeng'password = '123456'db = 'XKD_Python_Course'conn_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)engine = create_engine(conn_str, echo=False)# 创建会话,用于提交数据Session = sessionmaker(bind=engine)session = Session()teacher = session.query(Teacher).get(4)teacher.name = 'Robby'teacher.age = '99'session.commit()
where条件查询
from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, String, DATE, Enum, ForeignKeyimport enumfrom sqlalchemy.orm import sessionmakerBase = declarative_base()class My_Enum(enum.Enum): M = 'M' F = 'F'# 实体类class Emploee(Base): ''' +------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+---------------+------+-----+---------+-------+ | emp_no | int(11) | NO | PRI | NULL | | | birth_date | date | NO | | NULL | | | first_name | varchar(14) | NO | | NULL | | | last_name | varchar(16) | NO | | NULL | | | gender | enum('M','F') | NO | | NULL | | | hire_date | date | NO | | NULL | | +------------+---------------+------+-----+---------+-------+ ''' __tablename__ = 'employees' emp_no = Column(Integer, primary_key=True, nullable=False) birth_date = Column(DATE, nullable=False) first_name = Column(String(14), nullable=False) last_name = Column(String(16),nullable=False) gender = Column(Enum(My_Enum), nullable=False) hire_date = Column(DATE, nullable=False) def __repr__(self): return "emp_no='%s', birth_date='%s', first_name='%s', last_name='%s', gender='%s', hire_date='%s'" % (self.emp_no, self.birth_date, self.first_name, self.last_name, self.gender, self.hire_date) __str__ = __repr__# 创建连接引擎host = 'localhost'port = 3306username = 'zengzeng'password = '123456'db = 'XKD_Python_Course'conn_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)engine = create_engine(conn_str, echo=False)# 创建表Base.metadata.create_all(engine)# 创建会话,用于提交数据Session = sessionmaker(bind=engine)session = Session()# # 简单的where条件查询过滤, 返回可迭代对象, AND 取与emploees = session.query(Emploee).filter(Emploee.emp_no < 10010).filter(Emploee.gender == 'M')emploees = session.query(Emploee).filter((Emploee.emp_no > 10010) & (Emploee.gender == 'F'))# OR 取并emploees = session.query(Emploee).filter((Emploee.emp_no > 10010) | (Emploee.gender == 'F'))# NOT 取反emploees = session.query(Emploee).filter(~(Emploee.emp_no > 10010))# inemploees = session.query(Emploee).filter(Emploee.emp_no.in_([10010, 10011, 10012]))# not inemploees = session.query(Emploee).filter(~Emploee.emp_no.in_([10010, 10011, 10012]))# like ,like可以忽略大小写进行模式匹配emploees = session.query(Emploee).filter(Emploee.last_name.like('B%'))for emploee in emploees: print(emploee)
例如:emploees=session.query(Emploee).filter(Emploee.last_name.like('B%')).order_by(Emploee.emp_no.asc())
例如:emploees=session.query(Emploee).filter(Emploee.last_name.like('B%')).order_by(Emploee.emp_no.desc())
emploees = session.query(Emploee)print(list(emploees)) # 转化为列表print(emploees.count()) # 聚合count(*)查询print(emploees.all()) # 转化为列表print(emploees.limit(1).one()) # 查询首行
emploees = session.query(func.max(Emploee.emp_no))emploees = session.query(func.min(Emploee.emp_no))emploees = session.query(func.avg(Emploee.emp_no))
emploees = session.query(func.count(Emploee.emp_no)).group_by(Emploee.gender)print(emploees)for emploee in emploees: print(emploee)
参考:https://www.9xkd.com/user/plan-view.html?id=2415909403
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。