gpt4 book ai didi

python - 如何使用 Python 将 'NULL' 值插入 PostgreSQL 数据库?

转载 作者:IT老高 更新时间:2023-10-28 20:25:31 26 4
gpt4 key购买 nike

当变量在 Python 中为 None 时,将 NULL 键值输入到 PostgreSQL 数据库是否有一个好的做法?

运行此查询:

mycursor.execute('INSERT INTO products (user_id, city_id, product_id, quantity, price) VALUES (%i, %i, %i, %i, %f)' %(user_id, city_id, product_id, quantity, price))

user_idNone 时会导致 TypeError 异常。

当值为 None 时,如何使用 psycopg2 驱动程序将 NULL 插入数据库?

最佳答案

要将空值插入数据库,您有两种选择:

  1. 在您的 INSERT 语句中省略该字段,或
  2. 使用

另外:为防止 SQL 注入(inject),您不应在查询中使用普通字符串插值。

您应该将两 (2) 个参数传递给 execute(),例如:

mycursor.execute("""INSERT INTO products 
(city_id, product_id, quantity, price)
VALUES (%s, %s, %s, %s)""",
(city_id, product_id, quantity, price))

备选方案#2:

user_id = None
mycursor.execute("""INSERT INTO products
(user_id, city_id, product_id, quantity, price)
VALUES (%s, %s, %s, %s, %s)""",
(user_id, city_id, product_id, quantity, price))

关于python - 如何使用 Python 将 'NULL' 值插入 PostgreSQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4231491/

26 4 0
文章推荐: java - 哪个 list 实现对于一次写入、读取和销毁来说是最快的?