Python資料庫程式設計之索引
阿新 • • 發佈:2021-01-10
技術標籤:Python基礎及應用mysql資料庫pythonsql
文章目錄
實驗要求
實驗目的:是為了理解index在資料庫的作用,理解index的應用場合
- Python的SQL語句測試
請建立兩個一樣的學生表
學生表1,包含主鍵id(自增,學生id),學生姓名nane,學生成績score
學生表2,包含主鍵id(自增,學生id),學生姓名nane,學生成績score
請給學生表2的score新增index索引
關係型資料中加索引與不加索引的區別:
某個欄位建立索引會生成關於該欄位的樹形結構
即當使用where條件是:例如:where score > 90
- 不加索引: 順序查詢------>O(n)
- 加索引: 折半查詢------>O(log2n)
- 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())
- 總結:索引查詢適用於大量資料