未使用事务之前
-- 调用数据库
use test;
-- 先检查要使用的表是否存在,存在就删除
DROP TABLE IF EXISTS `testtable`;
-- 创建数据表
CREATE TABLE `testtable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`testname` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- 存储过程
delimiter $$
-- 如果存储过程存在,先删除
drop procedure if exists p1;
-- 创建
create procedure p1()
begin
-- 定义
declare i int;
declare user varchar(32);
-- 赋值
set i = 0;
set user = 'user';
-- 循环
while i < 10000 DO
-- CONCAT 字段拼接
insert into testtable(testname) values ( CONCAT( user , i));
set i = i + 1;
end while;
end$$
delimiter ;
-- 调用
call p1();
插入10000数据用时328秒
image.png
image.png
EXPLAIN SELECT * FROM testtable;
image.png
type:表示MySQL在表中找到所需行的方式,或者叫访问类型,常见类型如下(从左到右,性能由差到好)
ALL index range ref eq_ref const,system NULL
ALL: 全表扫描
index: 索引全扫描
range:索引范围扫描
ref:使用非唯一索引扫描
eq_ref:使用唯一索引扫描
const,system:单表中最多只有一个匹配行
创建普通索引:
ALTER TABLE 表名 ADD INDEX index_remark (remark);
image.png
使用事务之后插入100000条数据:
-- 调用数据库
use test;
-- 先检查要使用的表是否存在,存在就删除
DROP TABLE IF EXISTS `testtable`;
-- 创建数据表
CREATE TABLE `testtable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`testname` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- 存储过程
delimiter $$
-- 如果存储过程存在,先删除
drop procedure if exists p1;
-- 创建
create procedure p1()
begin
-- 定义
declare i int;
declare user varchar(32);
-- 赋值
set i = 0;
set user = 'user';
-- 循环
start transaction;#手动开启事务
while i < 10000 DO
-- CONCAT 字段拼接
insert into testtable(testname) values ( CONCAT( user , i));
set i = i + 1;
end while;
commit; #提交
end$$
delimiter ;
-- 调用
call p1();
image.png