xpa*_*nta 26 python postgresql null psycopg2 nonetype
NULL当变量None在Python中时,是否有一个很好的做法可以将键值输入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))
Run Code Online (Sandbox Code Playgroud)
结果在AA TypeError异常,当user_id是None.
如何使用驱动程序NULL将值插入到数据库中?Nonepsycopg2
ber*_*nie 45
要将空值插入数据库,您有两个选择:
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))
Run Code Online (Sandbox Code Playgroud)
备选方案#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))
Run Code Online (Sandbox Code Playgroud)
使用当前的 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31421 次 |
| 最近记录: |