Python数据库编程之索引


实验要求

实验目的:是为了理解index在数据库的作用,理解index的应用场合

  1. Python的SQL语句测试
    请创建两个一样的学生表
    学生表1,包含主键id(自增,学生id),学生姓名nane,学生成绩score
    学生表2,包含主键id(自增,学生id),学生姓名nane,学生成绩score
    请给学生表2的score添加index索引

关系型数据中加索引与不加索引的区别:
某个字段创建索引会生成关于该字段的树形结构
即当使用where条件是:例如:where score > 90

  • 不加索引: 顺序查找------>O(n)
  • 加索引   : 折半查找------>O(log2n)
  1. Python的 ORM方式执行测试
    请用ORM方式,在两个学生表中插入同样的数据-10万条,姓名生成采用汉字的随机组合方式,成绩采用0-100平均分布随机生成方式

对两个表同时执行查询大于95分成绩的学生,测试对score创建索引会不会带来查找时间效率的优势


一、SQL创建学生表

1.1 creat table

代码展示:

#Python 数据库
import pymysql

db = pymysql.connect(user='test',host='localhost', password='123456',database='testdb',charset='utf8')
cursor = db.cursor() #创建游标  游标的每个动作会执行到数据库里面

sql = """create table student1(
        id int auto_increment primary key,
        name varchar(20) not null,
        score int) """
cursor.execute(sql)
sql = """create table student2(
        id int auto_increment primary key,
        name varchar(20) not null,
        score int) """
cursor.execute(sql)
#添加索引
sql = "create index score_index on student2(score)"
#删除索引
#sql = "creat index score_index on student2()"
cursor.execute(sql)
cursor.close()
db.close()

结果展示:
在这里插入图片描述

1.2 show index

SHOW INDEX FROM student1 //未加索引

在这里插入图片描述

SHOW INDEX FROM student2 //加索引

在这里插入图片描述

二、ORM方式创建数据

2.1 建立数据

关键代码如下(示例):

#创建类
class Student1(Base):
    __tablename__ ='student1'#表名-->数据库中表student1

    id = Column(Integer, primary_key=True)
    name = Column(String)
    score = Column(Integer,default=60)#默认60

class Student2(Base):
    __tablename__ ='student2'#表名-->数据库中表student2

    id = Column(Integer, primary_key=True)
    name = Column(String)
.....
.....
.....
for i in range(100):
    #随机生成 两个字的姓名   分数 
    name  = ''.join(random.sample('张王天男别奥法妹大那几年安东尼的技能但是否能单反',2))
    score = random.randint(0,100)
    session.add(Student1(name=name, score=score))
    session.add(Student2(name=name, score=score)) 
    #每调用一次,塞入数据库执行一次    
    session.commit()
    '''
    由于插入数据需要消耗时间 当插入大量数据可作如下改动
    if i%10 == 0
    	session.commit()
    '''
    print(i)

2.2 查询数据

代码如下(示例):

#SqlAlchemy查询建立也需要时间
students = session.query(Student1).filter(Student1.score<50).all()
students = session.query(Student1).filter(Student2.score<50).all()
#SqlAlchemy真实测试的查询
#100条数据,不见索引查询的快
#1000条数据,建立索引查询的快
print(time.clock())
students = session.query(Student1).filter(Student1.score>90).all()
print(time.clock())
students = session.query(Student2).filter(Student2.score>90).all()
print(time.clock())
  • 总结:索引查询适用于大量数据

总结

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/HG0724/article/details/112404629