python - 如果表为空则执行 INSERT 多个值 POSTGRES

标签 python python-3.x postgresql psycopg2

我正在尝试在 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)

我使用的是python3和postgres10.5。我还看过this , thisthis但没有骰子。

最佳答案

使用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/

相关文章:

SQL Statement JOIN 只返回有关联的元素

python - 如何定义读取字符串元组的函数

python - 如何使用python将已编译的url转换为normail形式

python - 使用 Python/Cython 编写二进制文件的更快方法

python - 通过其属性之一的值返回列表元素

sql - 如何通过具有相同的ID进行分组?

python - 这怎么是一个非序列?

list - 需要澄清 python 中列表的扩展函数。请检查下面的代码

python - 有输入时如何计数

java - 按小时分组的表和平均值