python - Psycopg2 Postgres Unnesting a very long array to insert it into a tables column
问题描述
My database is on postgres and is local
I have an array that is in the form of:
[1,2,3,...2600]
As you can see it is a very long array so I cant type the elements one by one to insert them So I wanted to use unnest() function to make it like this:
1
2
3
|
2600
and maybe go from there however I still need to write the unnest like unnest(array [1,...,2600]) to work but ofcourse that didnt work
So how do I insert an array as rows of the same column at the same time?
解决方案
您可以使用execute_values
将所有数据批量放入表中:
import psycopg2
from psycopg2.extras import execute_values
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
insert_query = "insert into table_name (col_name) values %s"
# create payload as list of tuples
data = [(i,) for i in range(1, 2601)]
execute_values(cursor, insert_query, data)
conn.commit()
推荐阅读
- r - 当需要考虑机器公差时,按数字列合并 data.tables
- matlab - Outerjoin 未按预期合并,我的规范是否错误?
- java - Spring Boot React js 上传文件
- flutter - 带有 mixin 飞镖颤动的抽象类
- r - 尝试使用 ggplot 制作条形图时出错,这是怎么回事?
- python - 在python中读取一行的文件
- python - 在函数外部使用变量(Python)
- vue.js - Vue 和 TinyMCE 问题
- arrays - 如何使用快速字符串在没有条件跳转的情况下找到数组中的最大非重复元素?
- javascript - 我的 setInterval 正在生成错误“2VM6:1 Uncaught ReferenceError: timer is not defined at
:1:1"