背景
想在个人电脑上验证一些sql优化、各种主键的效果,只有在数据到达一定量级,才能明显的体现出来。所以第一步需要往数据库中写入大量数据
写入数据
值得注意的是,postgres建表时是区分大小写的,但是在查询的时候又是不区分大小写的,就像把写在sql里的大写自动替换成小写。
建表SQL
create table sell (
id serial,
name varchar,
weight int,
unitprice int,
constraint sell_seq primary key (id)
)
python写入postgres脚本
# 导入psycopg2包
import time
import psycopg2
from random import choice, randint
# 连接到一个给定的数据库
conn = psycopg2.connect(database="test",
user="postgres",
password="123456",
host="127.0.0.1",
port="5432")
# 建立游标,用来执行数据库操作
cursor = conn.cursor()
def insert_batch():
t = time.time()
values = []
name = "苹果 橘子 香蕉 柚子 菠萝 桃子 荔枝 龙眼 火龙果 梨子 西瓜 圣女果 榴莲 波罗蜜".split(" ")
for i in range(10000):
values.append("('{}',{},{})".format(choice(name), randint(1, 100), randint(1, 100)))
sql = "insert into sell (name, weight, unitprice) values " + ",".join(values)
cursor.execute(sql)
conn.commit()
print("insert batch用时: {}".format(time.time() - t))
if __name__ == '__main__':
try:
insert_batch()
except Exception as e:
# 关闭游标
cursor.close()
# 关闭数据库连接
conn.close()
raise e