在Python中,当变量为None时,是否有向PostgreSQL数据库输入NULL个键值的良好实践?

运行此查询:

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. 使用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))

Postgresql相关问答推荐

包含JSONB属性的过滤器的索引策略

sqlalchemy在Flask 下运行时出现无法解释的错误

忽略 split_part 的第 n 个分隔符之后

如何在postgresql中按时间查询

MERGE 语句的锁定级别

查找最小值和最大值

Psycopg2 在大型 Select 查询中耗尽内存

更详细地解释 JOIN 与 LEFT JOIN 和 WHERE 条件性能建议

什么是 postgres 超级用户

MAC OS X 上的 Postgres 权限被拒绝

如何使用 node-postgres 将多行正确插入 PG?

使用 pg_dump 和 psql -U postgres db_name < ... 移动数据库会导致ERROR: relation "table_name" does not exist

POSTGRESQL 中的 CHARINDEX (SQL SERVER) 相似函数是什么?

向 Postgres 整数数组添加值

null 计算结果为 false 的情况

错误:prepared statement "S_1" already exists

防止 PostgreSQL 中的递归触发器

如何在 postgres 查询中排名

PostgreSQL - 如何在不同时区呈现日期?

postgresql NOT ILIKE 子句不包含空字符串值