一、创建测试数据库

CREATE database example;

use example;
create TABLE `user` (
`id` int() NOT NULL,
`last_name` varchar() DEFAULT NULL,
`first_name` varchar() DEFAULT NULL,
`sex` set('M','F') DEFAULT NULL,
`age` tinyint() DEFAULT NULL,
`phone` varchar() DEFAULT NULL,
`address` varchar() DEFAULT NULL,
`password` varchar() DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_last_first_name_age` (`last_name`,`first_name`,`age`) USING BTREE,
KEY `idx_phone` (`phone`) USING BTREE,
KEY `idx_create_time` (`create_time`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二、使用Python3.6产生测试数据

1、ChangePipSource.py 作用:加快PIP的安装速度,原理:使用豆瓣的镜像

import os

ini = """[global]
index-url = https://pypi.doubanio.com/simple/
[install]
trusted-host=pypi.doubanio.com
disable-pip-version-check = true
timeout =
"""
pippath = os.environ["USERPROFILE"] + "\\pip\\" if not os.path.exists(pippath):
os.mkdir(pippath) with open(pippath + "pip.ini", "w+") as f:
f.write(ini)

2、生成测试数据的脚本

(1)Util/Config.py

class InitConfig:
DataBaseHost = '127.0.0.1'
DataBasePort =
DataBaseUser = 'root'
DataBasePassword = 'dsideal'
DataBaseName = "example"

(2)Util/MySQLHelper.py

# --encoding:utf---
# pip install pymysql
import pymysql.cursors
from Util.Config import * class MySQLHelper:
myVersion = 0.1 def __init__(self, host=InitConfig.DataBaseHost, port=InitConfig.DataBasePort, user=InitConfig.DataBaseUser,
password=InitConfig.DataBasePassword, db=InitConfig.DataBaseName, charset="utf8"):
self.host = host
self.user = user
self.port = port
self.password = password
self.charset = charset
self.db = db try:
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.password,
db=self.db, charset=self.charset, cursorclass=pymysql.cursors.DictCursor)
self.cursor = self.conn.cursor()
except Exception as e:
print('MySql Error : %d %s' % (e.args[], e.args[])) def query(self, sql):
try:
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
except Exception as e:
print('MySql Error: %s SQL: %s' % (e, sql)) def execute(self, sql):
try:
self.cursor.execute(sql)
self.conn.commit()
except Exception as e:
print('MySql Error: %s SQL: %s' % (e, sql)) def executemany(self, sql, data):
try:
self.cursor.executemany(sql, data)
self.conn.commit()
except Exception as e:
print('MySql Error: %s SQL: %s' % (e, sql)) def close(self):
self.cursor.close()
self.conn.close()

(3)generate_user_data.py

#!/usr/bin/python
# -*- coding: UTF- -*-
import random
import string
import time
from Util.MySQLHelper import * #批量插的次数
loop_count =
#每次批量查的数据量
batch_size =
success_count =
fails_count =
#数据库的连接
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
digits = ''
def random_generate_string(length):
return ''.join(random.sample(chars, length))
def random_generate_number(length):
if length > len(digits):
digit_list = random.sample(digits, len(digits))
digit_list.append(random.choice(digits))
return ''.join(digit_list)
return ''.join(random.sample(digits, length))
def random_generate_data(num):
c = [num]
phone_num_seed =
def _random_generate_data():
c[] +=
return (
c[],
"last_name_" + str(random.randrange()),
"first_name_" + str(random.randrange()),
random.choice('MF'),
random.randint(, ),
phone_num_seed + c[],
random_generate_string(),
random_generate_string(),
time.strftime("%Y-%m-%d %H:%M:%S")
)
return _random_generate_data
def execute_many(insert_sql, batch_data):
db = MySQLHelper()
db.executemany(insert_sql, batch_data)
db.close()
try:
#user表列的数量
column_count = #插入的SQL
insert_sql = "replace into user(id, last_name, first_name, sex, age, phone, address, password, create_time) values (" + ",".join([ "%s" for x in range(column_count)]) + ")"
batch_count =
begin_time = time.time()
for x in range(loop_count):
batch_count = x * batch_size
gen_fun = random_generate_data(batch_count)
batch_data = [gen_fun() for x in range(batch_size)]
execute_many(insert_sql, batch_data)
success_count=success_count+batch_size
print("Running..."+str(success_count))
end_time = time.time()
total_sec = end_time - begin_time
qps = success_count / total_sec
print("总共生成数据: " + str(success_count))
print("总共耗时(s): " + str(total_sec))
print("QPS: " + str(qps))
except Exception as e:
print(e)
raise
else:
pass
finally:
pass

3、将生成的100W条测试数据导出生成CSV

select id,last_name,first_name,sex,age,phone,address,password,create_time from user into outfile 'd://user.csv' fields terminated by ',' optionally enclosed by '"' escaped by '"'   lines terminated by '\r\n';

4、测试导入

truncate table user;

load data infile 'd://user.csv' into table `user`   fields terminated by ','  optionally enclosed by '"' escaped by '"'  lines terminated by '\r\n';

5、测试一下系统中的大表

load data infile '/usr/local/t_resource_info.csv' into table `t_resource_info`   fields terminated by ','  optionally enclosed by '"' escaped by '"'  lines terminated by '\r\n';

/*
1、导出
受影响的行: 822445
时间: 26.410s
985.91MB 2、导入
受影响的行: 822445
时间: 257.772s
*/

对比发下PSC的t_resource_info的备份时间:

6、下一步的思考 思路

http://www.cnblogs.com/obullxl/archive/2012/06/11/jdbc-mysql-load-data-infile.html

Mysql快速导出导入数据的实验的更多相关文章

  1. MySQL 之 导出导入数据

    导出数据库(sql脚本)  mysqldump -u 用户名 -p 数据库名 > 导出的文件名mysqldump -u root -p --databases db_name > test ...

  2. 使用 Navicat 8.0 管理mysql数据库(导出导入数据)

    http://dxcns.blog.51cto.com/1426423/367105 使用Navicat For MySql 将mysql中的数据导出,包括数据库表创建脚本和数据 (1)数据的导出:右 ...

  3. mysql命令导出导入数据和结构

    在命令行下mysql的数据导出有个很好用命令mysqldump,它的参数有一大把,可以这样查看: mysqldump 最常用的: mysqldump -uroot -pmysql databasefo ...

  4. GreenPlum/postgres copy命令导出/导入数据

    一.COPY命令简单实用 1.copy在postgres与GreenPlum介绍 1.1 postgrespostgres的COPY命令可以快速的导出/导入数据到postgresql数据库中,支持常用 ...

  5. mysql加速source导入数据

    mysql加速source导入数据 # 进入mysql中执行如下 ; ; ; ; -- 你的sql语句1 -- 你的sql语句2 -- 你的sql语句3 ; ; ; ;

  6. mysql导出导入数据

    使用sql语句导出数据: 导出时如果不写绝对路径,会提示The MySQL server is running with the --secure-file-priv option so it can ...

  7. Mysql 用命令行导出导入数据方法

    方法一: 导出参考:https://www.cnblogs.com/activiti/p/6700044.html 用mysqldump可以导出整个数据库里的表和数据,不单单是只导出某个表的数据 命令 ...

  8. 用命令从mysql中导出/导入表结构及数据

    在命令行下mysql的数据导出有个很好用命令mysqldump,它的参数有一大把,可以这样查看:mysqldump最常用的:mysqldump -uroot -pmysql databasefoo t ...

  9. mysql 命令行导出导入数据

    导出数据库(sql脚本)  mysqldump -u 用户名 -p 数据库名 > 导出的文件名mysqldump -u root -p --databases db_name > test ...

随机推荐

  1. xml解析标签

    //获取两个标签之间的值 private static string GetStr(string message, string strStart, string strEnd) { ; ; star ...

  2. lintcode-127-拓扑排序

    127-拓扑排序 给定一个有向图,图节点的拓扑排序被定义为: 对于每条有向边A--> B,则A必须排在B之前 拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点 找到给定图的任一拓扑排 ...

  3. [STL] STL各容器实现原理

    STL共有六大组件1.容器 2.算法 3.迭代器 4.仿函数 6.适配器 STL容器的实现原理 STL来管理数据十分方便,省去了我们自己构建数据结构的时间.其实,STL的实现也是基于我们常见的数据结构 ...

  4. 【bzoj2783】[JLOI2012]树 树上倍增

    题目描述 在这个问题中,给定一个值S和一棵树.在树的每个节点有一个正整数,问有多少条路径的节点总和达到S.路径中节点的深度必须是升序的.节点1是根节点,根的深度是0,它的儿子节点的深度为1.路径不必一 ...

  5. HDU 3446 有贪心思想的01背包

    Proud Merchants Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others) ...

  6. event loop 小记

    水平不够,只能整理一下知乎大神的回答,勉强度日这样子 在一个事件循环里,会有两个主要的队列:task queue 和 micro-task quene. 其中 task 包括: script(整体代码 ...

  7. [POI2014] KUR-Couriers(洛谷P3567)

    洛谷题目链接:[POI2014]KUR-Couriers 题目描述 Byteasar works for the BAJ company, which sells computer games. Th ...

  8. 「6月雅礼集训 2017 Day1」看无可看

    [题目大意] 给出n个数,a[1]...a[n],称作集合S,求

  9. [bzoj3306]树——树上倍增+dfs序+线段树

    Brief Description 您需要写一种数据结构,支持: 更改一个点的点权 求一个子树的最小点权 换根 Algorithm Design 我们先忽略第三个要求. 看到要求子树的最小点权,我们想 ...

  10. 密码字典生成工具crunch的简单使用

      案例1: crunch 1 8 #生成最小1位,最大8位,由26个小写字母为元素的所有组合   案例2: crunch 1 6 abcdefg #生成最小为1,最大为6.由abcdefg为元素的所 ...