【问题标题】:How to insert 'NULL' values into PostgreSQL database using Python?如何使用 Python 将“NULL”值插入 PostgreSQL 数据库?
【发布时间】:2011-05-13 00:03:32
【问题描述】:

当 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 插入数据库?

【问题讨论】:

  • 您使用的是哪个 DB-API 适配器?
  • 通过 DB-API 适配器我想你的意思是 db 接口 psycopg2。如果没有,你能更具体一点吗?

标签: python postgresql null psycopg2 nonetype


【解决方案1】:

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

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

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

您应该将两 (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 中的字符串插值可能导致 sql 注入。这很有趣,我还没有想到。
  • 不客气。这很好地描述了 SQL 注入攻击是什么:en.wikipedia.org/wiki/SQL_injection 这与字符串插值有什么关系?:假设您收到不可信的程序输入。例如,该输入可能包含DROP TABLE 命令。
  • 我使用 None 作为列值,但出现错误:ProgrammingError: column "none" does not exist LINE 1: ...01.00-ng20', report_date='2016-03-30 ', ec_enabled=None, ec_s... 这是失败的原始查询:UPDATE kw_daily_data_mart SET hostname='ctrlkey.com', users_licensed=7, license_users=10, sw_version='kw2016.01.00-ng20', report_date='2016 -03-30', ec_enabled=None, ec_server_count=1, config_max_file_version=10, av_enabled=True, location_count=1, sso_enabled=False WHERE customer_id=127892 AND installation_id=3585 AND hostname='ctrlkey.com' 返回 id
  • 我也在使用 None,我得到与 @Varun 相同的错误。相同的 python 包 psycopg2,v2.6.2。 Posgresql v9.6
  • 解决方案也适用于更新查询。感谢分享!
【解决方案2】:

使用当前的 psycopg,而不是 None,使用设置为 'NULL' 的变量。

variable = 'NULL'
insert_query = """insert into my_table values(date'{}',{},{})"""
format_query = insert_query.format('9999-12-31', variable, variable)
curr.execute(format_query)
conn.commit()

>> insert into my_table values(date'9999-12-31',NULL,NULL)

【讨论】:

  • 这适用于 psycopg2 2.8.4,插入 None 的解决方案最终在 db 中的值为 'None',至少对于 postgres 而言
  • 如果要插入的字段是文本字段,使用'NULL',只需插入这四个字符。上面的答案(使用None)是正确的。
【解决方案3】:

这是我的解决方案:

text = '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))

text = text.replace("nan", "null")

mycursor.execute(text)

【讨论】:

    【解决方案4】:

    一种更简单的方法,也适用于大量列:

    row 是要插入的值列表,其中可能包含None。要将其插入 PostgreSQL,我们执行以下操作

    values = ','.join(["'" + str(i) + "'" if i else 'NULL' for i in row])
    cursor.execute('insert into myTable VALUES ({});'.format(values))
    conn.commit()
    

    【讨论】:

    • 也许题外话了,但我建议不要在不指定列名的情况下插入表。
    猜你喜欢
    • 2019-02-22
    • 2023-03-08
    • 2021-10-16
    • 2019-12-02
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多