歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用Python隨機生成數據再插入到PostgreSQL中

用Python隨機生成數據再插入到PostgreSQL中

日期:2017/3/1 9:13:38   编辑:Linux編程

用Python隨機生成學生姓名,三科成績和班級數據,再插入到PostgreSQL中。

模塊用psycopg2 random

import random
import psycopg2

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

# 數據庫連接參數
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,glass))
    
    conn.commit()    #提交命令,否則數據庫不執行插入操作
    
cur.close()
conn.close()

random.choice(序列):在一個序列中隨機選取一個元素

Ubuntu 14.04安裝Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved