Python randomly generates data and inserts it into PostgreSQL and pythonpostgresql.

Source: Internet
Author: User

Python randomly generates data and inserts it into PostgreSQL and pythonpostgresql.

Use Python to randomly generate student names, scores of three subjects and class data, and then insert them into PostgreSQL.

ModulePsycopg2 random

Import randomimport psycopg2fname = ['King', 'zhao ', 'lil', 'chen', 'xu ', 'long', 'King', 'high ', 'zhang ', 'hou', 'ai', 'Qian ', 'sun', 'zhou', 'zheng'] mname = ['yu ', 'ming ', 'ling', 'shu', 'hangzhou', 'anyap', 'day', '小', 'wind', 'rain', 'snow', 'day ', 'water', 'Q', 'whale ', 'meters', 'xiao ', 'ze', 'n', 'ge', 'xuan', 'dao ', 'zhen ', 'long', 'qy'] lname = ['', 'ling','', 'fang', 'ming', 'hong ', 'country ', 'fin', '', 'yun', 'yun ', 'yin','', 'hua ', 'Ye ','', 'huang', 'ali', 'jin', 'hangzhou', 'jun', '', 'in ','', 'OK'] # database connection parameter conn = psycopg2.connect (database = "girl", user = "jm", password = "123", host = "127.0.0.1 ", port = & quot; 5432 & quot;) cur = conn. cursor () for x in range (200): # generate random data 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) # insert data (note that % d cannot be used only for % s. For numeric data, use cur.exe cute ("insert into score values (% s, % s, % s, % s) ", (x, pname, math, english, chinese, glass) conn. commit () # submit the command, otherwise the database will not execute the insert operation cur. close () conn. close ()

The above is all the content that is randomly generated using Python and inserted into the PostgreSQL database. We hope to help you learn Python and PostgreSQL.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.