【问题标题】:How to insert NULL values into PostgreSQL database using Python?如何使用 Python 将 NULL 值插入 PostgreSQL 数据库?
【发布时间】:2019-02-22 18:03:55
【问题描述】:

我有这样的数据元组列表:

list1 = [(1100, 'abc', '{"1209": "Y", "1210": "Y"}'), (1100, 'abc', None)]

def insert_sample_data(col_val):
    cur = self.con.cursor()
    sql = """insert into sampletable values {}""".format(col_val)
    cur.execute(sql)
    self.con.commit()
    cur.close()

values1 = ', '.join(map(str, list1))  #bulk insert
insert_sample_data(values1)

表结构: ssid int,名称 varchar,规则 jsonb

当我尝试插入数据但它抛出一个错误说“插入列“无”不存在”。我们如何将数据加载到“Null”或“None”的表中?

我查看了这个解决方案,但在这种情况下它没有帮助 How to insert 'NULL' values into PostgreSQL database using Python?

【问题讨论】:

  • 为什么链接问题的解决方案在这种情况下不起作用?因为批量插入?为此,如果速度对您很重要,您应该使用 executemanyexecute_batch

标签: python python-3.x postgresql


【解决方案1】:

正如@shmee 所说,您需要使用executemany 之类的东西并参数化您的值,而不是使用容易受到SQL 注入攻击的format

我会修改你的代码如下:

def insert_sample_data(self, values): # added self since you are referencing it below
    with self.con.cursor() as cur:
        sql = "insert into sampletable values (%s, %s, %s)" # Use %s for parameters
        cur.executemany(sql, values) # Pass the list of tuples directly
        self.con.commit()

list1 = [(1100, 'abc', '{"1209": "Y", "1210": "Y"}'), (1100, 'abc', None)]
self.insert_sample_data(list1) # pass the list directly

【讨论】:

  • 正如@shmee 所说,速度对我的流程来说非常重要,因为要插入至少 100k 到 100 万条记录,并且使用 executemany 需要很多时间。我对你的代码做了一些修改,它就像一个魅力。谢谢@Nicarus
猜你喜欢
  • 2011-05-13
  • 2023-03-08
  • 2021-10-16
  • 2019-12-02
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多