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.