使用python将多值插入postgresql

rjzwgtxy  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(160)

我想为postgresql构建一个多值插入,如下所示:

INSERT INTO mytable 
VALUES 
    (<value a>, <value b>, …, <value x>),
    (<value 1>, <value 2>, …, <value n>),
    (<value A>, <value B>, …, <value Z>)

我有一本有元组的字典。
如何构建“正确的”插入语句?如何去掉括号.. -〉[ ]

>>> 'INSERT INTO mytable VALUES%s' % [f for f in foo]
'INSERT INTO mytable VALUES[(1, 2, 3), (4, 5, 6), (7, 8, 9)]'
jv4diomz

jv4diomz1#

使用其中一个快速执行助手,它比executemany * 更快 *。
执行值(_V):

import psycopg2
from psycopg2.extras import execute_values

with psycopg2.connect(database='test') as conn:      
    with conn.cursor() as cur:        
        execute_values(cur, """INSERT INTO t74179514 (a, b, c) VALUES %s""", foo)

执行批次(_B):

import psycopg2
from psycopg2.extras import execute_batch

with psycopg2.connect(database='test') as conn:      
    with conn.cursor() as cur:           
        execute_batch(cur, """INSERT INTO t74179514 (a, b, c) VALUES (%s, %s, %s)""", foo)

相关问题