当变量是Python中的NULL
时,是否有一个很好的做法可以将None
键值输入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))
当TypeError
是user_id
时,导致None
异常。
当值为NULL
时,如何使用None
驱动程序将psycopg2
插入数据库?
要将空值插入数据库,您有两个选择:
None
另外:为了防止SQL注入,您不应该对查询使用普通的字符串插值。
你应该向execute()
传递两(2)个参数,例如:
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))
使用当前的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)
是的,我将变量命名为'variable'。大呐喊,想要争吵吗?