码迷,mamicode.com
首页 > 编程语言 > 详细

利用python造数据

时间:2020-12-09 12:20:38      阅读:6      评论:0      收藏:0      [点我收藏+]

标签:语句   千万   执行   and   __name__   port   with open   设计   rgb   

# 利用python 生成造数据的sql语句,再去mysql中执行

import random
import time

# 构造表t_user_weight
def create_t_user_weight():
    start = time.time()
    # 定义需要生成的数据量
    count = 10000000  # 1千万
    beginID = 2020031
   # 打开文件,并动态生成sql数据,将数据存在文件中
    try:
        with open("./insert_t_user_weight.txt", "wb") as fo:
            length = count + 1
            for i in range(1, length):
                # 定义数据,以下只是测试数据,可以根据自己的业务通过调用函数去随机生成对应的值
                id = str(i)
                userId = str(beginID + i)
                name = ‘‘.join(random.sample(zyxwvutsrqponmlkjihgfedcba, 4)).replace(‘‘, ‘‘)
                sex = str(random.choice([, ]))
                weight = str(random.randrange(10, 99))
                address = str(random.choice([北京, 上海, 深圳, 广州, 杭州]))
                insert_t_user_weight = (
                    "INSERT INTO t_user_weight VALUES (‘%s‘, ‘%s‘, ‘%s‘,‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘);"
                    % (id, userId, name, sex, weight, address, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                )
                insert_t_user_weight = insert_t_user_weight + \n
                # print(insert_t_user_weight)
                fo.write(insert_t_user_weight.encode(UTF-8))
            print(共创建1千万条sql耗时:, time.time() - start)
    except Exception as e:
        print(Exception, ":", e)

if __name__ == "__main__":
    create_t_user_weight()

以上为构造简单数据的python 脚本,若是需要构造多个表关联的数据,也是可以扩展的,只需要根据自己的需求微调或设计一些id再嵌套一个循环即可。

 

利用python造数据

标签:语句   千万   执行   and   __name__   port   with open   设计   rgb   

原文地址:https://www.cnblogs.com/lexus168/p/14088610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!