思路:先用代碼造數據,保存到一個文檔,然后將生成的數據一鍵復制到需要執行SQL的地方執行
一個簡單的案例:
目標:向數據庫 testsql 的 kemu_base 表中插入1W 條數據(這里是用 Navicat 連接的數據庫)
第一步:運行代碼造數據,保存到 1.txt 文檔(注:這里1.txt 與執行代碼的 .py 文件在同一個包的同一個目錄下)
# coding:utf-8 import random insert_sql = "INSERT INTO kemu_base(id, subjects, score) VALUES " with open("1.txt", "a") as fp: fp.write(insert_sql+"\n") for i in range(1, 10001): subjects = ['English', 'mathematics', 'Chinese', 'chemical', 'physical'] a = "('{0}', '{1}', '{2}'),".format(str(i), random.choice(subjects), random.randint(0, 100)) with open("1.txt", "a") as fp: fp.write(a+"\n")
1.txt 生成數據如下:
......
第二步:復制數據到編輯器中去執行
- 一鍵復制數據到 Navicat 中的查詢編輯器中,如下:
- 點擊運行,查看到執行成功,且用時很短
第三步:查看表,已成功生成數據
......
這樣生成1W條數據就完成了。
不論要添加多少條,同理,改改 range 的范圍即可,
不論有多少個字段,改改 str.format() 即可,format 函數可以接受不限個參數。
知識點:
import random print(random.randint(0, 100)) # 產生 0 到 100 的一個整數型隨機數 print(random.choice(subjects)) # 從序列中隨機選取一個元素 print(random.random()) # 產生 0 到 1 之間的隨機浮點數 print(random.uniform(1.7, 9.3)) # 產生 1.7 到 5.3 之間的隨機浮點數,區間可以不是整數 print(random.randrange(1, 100, 2) ) # 生成從 1 到 100 的間隔為 2 的隨機整數 s = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 將序列a中的元素順序打亂 random.shuffle(s) print(s)
格式化字符串的函數 str.format(),它增強了字符串格式化的功能;基本語法是通過 {} 和 : 來代替以前的 % 。 format 函數可以接受不限個參數,位置可以不按順序;實例如下: >>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序 'hello world' >>> "{0} {1}".format("hello", "world") # 設置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 設置指定位置 'world hello world'