Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Python 大量產生隨機成績資料並寫入 PostgreSQL

需要一批測試資料時,手動造資料既無聊又慢。這裡用 Python 隨機產生學生姓名、三科成績與班別,再批次寫進 PostgreSQL,幾十行就能搞定。

需要的模組

random 負責產生隨機值,psycopg2 負責與 PostgreSQL 溝通。

姓名怎麼湊出來

把中文姓名拆成三份清單:姓氏、名字中段、名字尾字,隨機各挑一個拼起來,就能組合出大量不重複的名字。

import random

fname = ['金','趙','李','陳','許','龍','王','高','張','侯','艾','錢','孫','周','鄭']
mname = ['玉','明','玲','淑','偑','艷','大','小','風','雨','雪','天','水','奇','鯨',
         '米','曉','澤','恩','葛','玄','道','振','隆']
lname = ['','玲','','芳','明','紅','國','芬','','雲','嫻','隱','','花','葉',
         '','黃','亮','錦','茑','軍','','印','','凱']

完整程式

import random
import psycopg2

conn = psycopg2.connect(database="girl", user="jm", password="123",
                        host="127.0.0.1", port="5432")
cur = conn.cursor()

for x in range(200):
    # 產生隨機資料
    pname = random.choice(fname) + random.choice(mname) + random.choice(lname)
    math = random.randint(40, 100)
    english = random.randint(40, 100)
    chinese = random.randint(40, 100)
    pclass = random.randint(1, 3)

    # 寫入資料:只能用 %s 佔位,不能用 %d;數值型欄位不加引號
    cur.execute(
        "insert into score values(%s,%s,%s,%s,%s,%s)",
        (x, pname, math, english, chinese, pclass)
    )
    conn.commit()   # 不提交,資料不會真正寫入

cur.close()
conn.close()

幾個實務提醒

  • random.choice(序列):從序列中隨機取一個元素。
  • random.randint(a, b):取 a 到 b 之間的整數,含頭含尾。
  • psycopg2 的參數佔位一律使用 %s,寫 %d 會出錯;而且用參數化寫法能順便避開 SQL injection。
  • commit() 別忘了,預設交易模式下不提交等於沒寫。
  • 資料量大時,不必每筆都 commit,累積一批再提交會快很多。
Copyright © Linux教程網 All Rights Reserved