当前位置:   article > 正文

python学习-第18课_base2= declarative_base() waring

base2= declarative_base() waring

一、复习

1.1.数据库操作(mysql)

1.1.1.创建数据库

语法:

create database db;
示例:
创建test数据库
create database test;


1.1.2.权限授权

语法:
grant all privileges on *.* to '用户名'@'%' identified by '登录密码';

示例:
创建admin(密码为123456)的用户,并授权,带可授权权限的
grant all privileges on *.* to 'admin'@'%' identified by '123456' with grant option;


1.1.3.创建表

语法:
create table tb(字段1 类型,字段2 类型,....)

示例:
创建student表,包含id(int类型),name(varchar),age(int类型),sex(枚举)
create table student(id int not null auto_increment primary_key,name varchar(50),age int,sex enum('F','G'));


1.1.3.增加数据

语法:
insert into tb(字段1,字段2,......) values(值1,值2,......)
示例:
向student表中插入数据
insert into student(name,age,sex) values("test01",15,"F"),("test02",26,"G"),("test03",24,"F"),("zhangsan",32,"G"),("lisi",45,"F");

1.1.4.查询数据

语法:
select 字段1,字段2 from 表名 where 条件1 and(or) 条件2
示例:
查出name包含test的name,age,sex信息
select * from student where name like '%test%'

1.1.5.修改数据

语法:

update 表名 set 字段名=新值 where 条件1;
示例:
将zhangsan的年龄修改为22
update student set age=22 where name='zhangsan';


1.1.6.删除数据

语法:

delete from 表名 where 条件1;
示例:
删除name为test03数据
delete from student where name='test03';


1.1.7.删除表

语法:
drop table 表名;
示例:
删除student表
drop table student;

1.1.8.join(联合查询)

语法:
select a.字段1,b.字段2 from 表1  a join 表2 b on a.id=b.id
示例:
select a.name teacher_name,b.name student_name from teacher a join relation_table c on a.id=c.teacher_id join student b on b.id = c.student_id;

1.1.9.创建索引

语法:
creat index idx_库名_表名_列名1_列名2 on 表名(列名1,列名2);
示例
创建student中的name,sex索引
create index  idx_test_student_name_sex on student(name,sex);

1.1.10.查看执行的SQL是走索引

语法:

explain sql语句;

示例:
explain select * from student;


1.2.python连接数据库

python2 默认使用的MySQLDB
python3使用的pymysql ,pymysql需要安装 pip install pymysql
示例:
第一步:创建数据库连接和游标,游标用于执行SQL
import pymysql
#创建数据库连接
conn=pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456",db="test")
#创建游标
cursor=conn.cursor()

第二步:执行SQL
 定义sql
sql = "select * from student"
# 执行
cursor.execute(sql)
# 取所有的结果,取结果之前,一定要先执行sql
cursor.fetchall()
# 取一个结果
# cursor.fetchone()
# 取10行数据
# cursor.fetchmany(size=10)

第三步:关闭游标和连接
#关闭游标
cursor.close()
#关闭连接
conn.close()

1.3.SQLAlchemy

1.3.1.创建表

示例
创建teacher表
#创建引擎
#mysql+pymysql://数据库登录名:数据库登录密码@数据库服务器IP/所使用的数据库名  +pymysql:python3专用
engine=create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
#使用元数据MetaData获取引擎
metadata=MetaData(engine)
#创建表模型  Table第一个参数为要创建表的表名,第二个参数为连接数据库的元数据,第三个以后的参数为创建表的字段
teacher=Table('teacher',metadata,
              Column("id",Integer,primary_key=True,autoincrement=True),
              Column("name",String(50)),
              Column("sex",Enum("F","G")),
              Column("course",String(100))
              )
#执行建表操作
metadata.create_all()

1.3.2.插入数据

示例
from sqlalchemy import create_engine, Column, String, Enum
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine=create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
#创建session工厂
DBSession = sessionmaker(bind=engine)
#创建一个session
session=DBSession()
base=declarative_base()
#创建对表teacher的模型
class Teacher(base):
     __tablename__='teacher'
     name=Column(String(50))
     sex=Column(Enum('F','G'))
     course=Column(String(100))
#引入模型,实例化数据
teacher1=Teacher("chen teacher","G","yuwen")
teacher2=Teacher("wang teacher","F","shuxue")
teacher3=Teacher("liu teacher","G","yingyu")
teacher4=Teacher("pan teacher","F","wuli")
teacher5=Teacher("xiang teacher","G","huaxue")
#向表中插入一条数据
session.add(teacher1)
#向表中插入多条数据
session.add_all([teacher2,teacher3,teacher4,teacher5])
#提交操作
session.commit()
#关闭session
session.close()

1.3.3.查询数据

1.过滤filter()
示例
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))

def select(session):
    result = session.query(Student). filter(Student.name == 'lisi').one()
    print(result.name, result.age, result.sex)

def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    select(session)

if __name__ == '__main__':
    main()


2.过滤filter_by()

from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))

def select(session):
    result = session.query(Student). filter_by(name = 'lisi').all()
    print(result.name, result.age, result.sex)

def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    select(session)

if __name__ == '__main__':
    main()

3.filter()和filter_by()区别
filter:可以使用使用<  >  ==等,但条件格式必须为:表.列,不支持组合查询
filter_by():可以直接写列,不支持 < >,支持组合查询

4.模糊查询
示例
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))

def select(session):
    result = session.query(Student) .filter(Student.name.like('test%'))
    for i in result:
        print(i.id,i.name,i.age,i.sex)

def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    select(session)

if __name__ == '__main__':
    main()

4.获取数据的两种方法one() 和 all()

one()返回的结果是元组tuple()
all()返回的结果是list,list里面包含若干个元组tuple

1.3.4.更新数据

更新的流程为:
1.先查出来
2.更新一个类所对应的属性值
3.提交
示例
将id为2的name修改为updatename

from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base = declarative_base()
class Student(base):
    __tablename__ = 'student'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    age = Column(Integer)
    sex = Column(Enum('F', 'G'))

def update(session):
    result = session.query(Student).filter(Student.id == 2).one()
    result.name="updatename"
    session.commit()

def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    # 更新
    update(session)

if __name__ == '__main__':
    main()


1.3.5.删除数据

删除数据流程:
1.先查询
2.再直接调用delete()
3.提交

示例
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base = declarative_base()
class Student(base):
    __tablename__ = 'student'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    age = Column(Integer)
    sex = Column(Enum('F', 'G'))

def delete(session):
    session.query(Student).filter(Student.id == 5) .delete()
    session.commit()


def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    # 更新
    delete(session)


if __name__ == '__main__':
    main()

1.3.6.统计、分组、排序

1.3.6.1 统计count
示例

统计年龄为22的人数
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))

def select(session):
    number = session.query(Student).filter(Student.age==22).count()
    print(number)


def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    select(session)

if __name__ == '__main__':
    main()

1.3.6.2. 分组group_by
示例
按年龄分组
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))

def select(session):
    result = session.query(Student).group_by(Student.age).all()
    for i in result:
        print(i.id,i.name,i.age,i.sex)

def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    select(session)

if __name__ == '__main__':
    main()
结果:

1.3.6.3. 排序order_by
示例1:
按年龄排序(默认为升序排序)
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))

def orderBy(session):
    result = session.query(Student). order_by(Student.age).all()
    for i in result:
        print(i.id,i.name,i.age,i.sex)

def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    orderBy(session)

if __name__ == '__main__':
    main()
结果


示例2:
按年龄排序(默认为升序排序)
from sqlalchemy import create_engine, Column, String, Enum, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


base=declarative_base()
class Student(base):
    __tablename__='student'
    id=Column(Integer,primary_key=True)
    name=Column(String(50))
    age=Column(Integer)
    sex=Column(Enum('F','G'))


def orderBy(session):
    result = session.query(Student). order_by(Student.age.desc()).all()
    for i in result:
        print(i.id,i.name,i.age,i.sex)


def main():
    engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/test')
    # 创建session工厂
    DBSession = sessionmaker(bind=engine)
    # 创建一个session
    session = DBSession()
    #查询
    orderBy(session)


if __name__ == '__main__':
    main()
结果:



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/181007
推荐阅读
相关标签
  

闽ICP备14008679号