Python隨機產生資料後插入到PostgreSQL,pythonpostgresql

來源:互聯網
上載者:User

Python隨機產生資料後插入到PostgreSQL,pythonpostgresql

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

模組用psycopg2 random

import randomimport psycopg2fname=['金','趙','李','陳','許','龍','王','高','張','侯','艾','錢','孫','周','鄭']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()

以上就是利用Python隨機產生資料後插入到PostgreSQL資料庫中的全部內容,希望給大家學習Python及PostgreSQL帶來協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.