我正在尝试在 postgres 表中添加一些默认值。我可以添加 1 个值,但我想添加 5 个默认值。我在下面尝试过此操作,但它仅创建一个值,因为插入第一个值后,空条件不再有效。
records_to_insert = [( 1,'foo', 30, 2, True),
( 2,'bar', 60, 3, False),
( 3,'hero', 95, 2, False),
( 4,'borth', 45, 1, True),
( 5,'here', 30, 2, True)]
sql_insert_query = """ INSERT INTO tester (id, name, time, rating,others)
SELECT %s,%s,%s,%s,%s
WHERE NOT EXISTS (SELECT * FROM tester) """
cursor = connection.cursor()
#executemany() to insert 3 rows
result = cursor.executemany(sql_insert_query, records_to_insert)
最佳答案
使用psycopg2.extras.execute_values(cur, sql, argslist, template=None, page_size=100)
Execute a statement using VALUES with a sequence of parameters. Parameters:
- cur – the cursor to use to execute the query.
- sql – the query to execute. It must contain a single %s placeholder, which will be replaced by a VALUES list. (...)
您应该重新编写查询以使用VALUES
:
from psycopg2.extras import execute_values
sql_insert_query = """
INSERT INTO tester (id, name, time, rating, others)
SELECT * FROM (VALUES %s) s
WHERE NOT EXISTS (SELECT 1 FROM tester) """
execute_values(cursor, sql_insert_query, records_to_insert)
关于python - 如果表为空则执行 INSERT 多个值 POSTGRES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910643/