weixin_46523951 2021-07-07 23:24 采纳率: 75%

# postgresql如何循环读取填充同一张表

6 2 8

• 写回答

#### 1条回答默认 最新

• blkq 2021-07-08 00:52
关注

直接写sql不好搞，除非是存储过程。
用其它语言生成sql语句是最简单，比如用python:

``````class Fibonacci(object):

def __init__(self, n):
self.n = n
self.current = 0
self.a = 14
self.b = 8

def __next__(self):
if self.current == 0:
self.current += 1
return self.a

if self.current < self.n:
self.a, self.b = self.b, self.a + self.b
self.current += 1
return self.a
else:
raise StopIteration

def __iter__(self):
return self

if __name__ == '__main__':
day = 1
fib = Fibonacci(30)
# INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
for num in fib:
print(f"insert into oth.power (month，day，fee) values (6, {day}, {num});")
day += 1
``````

结果是：

``````insert into oth.power (month，day，fee) values (6, 1, 14);
insert into oth.power (month，day，fee) values (6, 2, 8);
insert into oth.power (month，day，fee) values (6, 3, 22);
insert into oth.power (month，day，fee) values (6, 4, 30);
insert into oth.power (month，day，fee) values (6, 5, 52);
insert into oth.power (month，day，fee) values (6, 6, 82);
insert into oth.power (month，day，fee) values (6, 7, 134);
insert into oth.power (month，day，fee) values (6, 8, 216);
insert into oth.power (month，day，fee) values (6, 9, 350);
insert into oth.power (month，day，fee) values (6, 10, 566);
insert into oth.power (month，day，fee) values (6, 11, 916);
insert into oth.power (month，day，fee) values (6, 12, 1482);
insert into oth.power (month，day，fee) values (6, 13, 2398);
insert into oth.power (month，day，fee) values (6, 14, 3880);
insert into oth.power (month，day，fee) values (6, 15, 6278);
insert into oth.power (month，day，fee) values (6, 16, 10158);
insert into oth.power (month，day，fee) values (6, 17, 16436);
insert into oth.power (month，day，fee) values (6, 18, 26594);
insert into oth.power (month，day，fee) values (6, 19, 43030);
insert into oth.power (month，day，fee) values (6, 20, 69624);
insert into oth.power (month，day，fee) values (6, 21, 112654);
insert into oth.power (month，day，fee) values (6, 22, 182278);
insert into oth.power (month，day，fee) values (6, 23, 294932);
insert into oth.power (month，day，fee) values (6, 24, 477210);
insert into oth.power (month，day，fee) values (6, 25, 772142);
insert into oth.power (month，day，fee) values (6, 26, 1249352);
insert into oth.power (month，day，fee) values (6, 27, 2021494);
insert into oth.power (month，day，fee) values (6, 28, 3270846);
insert into oth.power (month，day，fee) values (6, 29, 5292340);
insert into oth.power (month，day，fee) values (6, 30, 8563186);
``````

然后把生成好的sql去数据库执行一下就好了

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥20 微信h5网页如何静默获取到用户的基本信息（头像昵称）
• ¥15 有做通信软件的技术团队吗
• ¥15 如图所示交换机网络该如何规划配置
• ¥15 CUDA driver error
• ¥15 Dijkstra 算法的堆优化方法
• ¥15 师哥师姐们，如何帮我下载一下python？
• ¥15 Office版本升级，Oracle连接报错
• ¥20 利用python搜索PDF文件中是否存在1
• ¥15 ImportPathMismatchError
• ¥15 滤波器这个效果是对的么