在Python中NULL使用变量时,是否存在将键值输入PostgreSQL数据库的好习惯None?
NULL
None
运行此查询:
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))
是TypeError时user_id会导致aa异常None。
TypeError
user_id
使用驱动程序如何将aNULL插入到数据库中?None``psycopg2
None``psycopg2
要将空值插入数据库,您有两个选择:
另外:为了防止SQL注入,您不应在查询中使用普通的字符串插值。
您应该将两(2)个参数传递给execute(),例如:
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))