快速生成千萬條mysql資料

2021-12-30 07:28:38 字數 1569 閱讀 5389

學習、測試mysql海量資料的場景,需要先生成資料。

mysql官方文件說得很清楚。」load data infile」匯入資料比insert要快20倍。所以我們先生成一千萬條資料的檔案。

然後將資料匯入表中。

假如有個使用者表(id, username,password, age, ***),id是自動增長,我們現在需要生成username等資訊

生成一千萬條資料,速度還能接受,耗時236秒,檔案大小315m。

import string

import random

def random_str(length=1):

template = string.letters + string.digits

chars = random.sample(template, length)

return "".join(chars)

def generate_record():

"""username/password/age/***

"""length = random.randint(6, 20)

username = random_str(length)

length = random.randint(6, 20)

password = random_str(length)

age = random.randint(10, 100)

*** = random.choice([0, 1])

return [username, password, age, ***]

def create_file(num=10000000):

with open("user_data.txt", "w") as f:

for i in range(num):

row = generate_record()

f.write(",".join(map(str, row))+"\n")

if __name__ == '__main__':

import datetime

start = datetime.datetime.now()

create_file()

end = datetime.datetime.now()

cost = (end -start).total_seconds()

print("cost: %s" % cost)

#一千萬條,耗時236s,檔案315mload data infile命令有安全限制,最好是把資料拿到mysql server端,再通過mysql -u*** -p***進入命令,再匯入。

我的虛擬機器匯入耗時57秒

load data infile "/user_data.txt" into table user

fields terminated by ','

lines terminated by '\n'

(username, password, age, ***);測試工具sysbench

sysbench是批量insert,效能比不上匯入。但是它更接近實際場景

儲存過程

速度很快,但是不如用熟悉的指令碼方便

mysql生成千萬級測試資料

mysql生成千萬級測試資料 為了更好的測試mysql效能以及程式優化,不得不去製作海量資料來測試。之前用儲存過程的方法。生成測試資料。特別慢。所以改為在服務端呼叫db生成 1.首先建立測試表 card表 create table card card id bigint 20 not null au...

SQL SERVER 快速插入千萬條資料

1.正常插入 插入非常慢。declare count int 10000000,index int 0 begin tran while index count begin insert into ordertest id values round rand 10000000,0 set index...

Mysql 千萬資料快速匯入

最近碰到個專案,需要 千萬條資料入庫的問題,有原本的 類 csv 檔案匯入,統計了下 資料行大概有 1400w 行之多 二話不說,建表,直接 load load data local infile data data.csv into table pk book price character se...