2010-11-20 153 views
13

当Python中的变量为None时,是否有将NULL键值输入到PostgreSQL数据库的良好做法?如何使用Python将'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)) 

导致一个TypeError异常,当user_idNone

当值为None时,如何使用psycopg2驱动程序将NULL插入到数据库中?

+0

哪个DB-API适配器您使用?由DB-API适配器编写的 – 2010-11-20 06:23:58

+0

我想你的意思是db接口psycopg2。如果不是,你可以更具体吗? – xpanta 2010-11-20 06:34:18

回答

27

要插入到数据库空值,你有两个选择:

  1. 省略从INSERT语句中那场,或
  2. 使用None

另外:为了防止SQL注入你不应该为你的查询使用普通的字符串插值。

你应该通过两(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)) 
+0

谢谢。你能指点我什么地方,所以我可以阅读为什么在Python中的字符串插值可能会导致SQL注入。这非常有趣,我没有想到这一点。 – xpanta 2010-11-20 07:17:49

+2

不客气。这很好地描述了SQL注入攻击是什么:http://en.wikipedia.org/wiki/SQL_injection这与字符串插值有什么关系?假设你接收到不可信任的输入到你的程序。该输入可以包含例如“DROP TABLE”命令。 – bernie 2010-11-20 07:29:03

+0

我使用None作为列值,但得到一个错误: ProgrammingError:column“none”does not exist LINE 1:... 01.00-ng20',report_date ='2016-03-30',ec_enabled =无,ec_s ... 以下是原始查询失败: UPDATE kw_daily_data_mart SET hostname ='ctrlkey.com',users_licensed = 7,licensed_users = 10,sw_version ='kw2016.01.00-ng20',report_date ='2016- 03-30',ec_enabled =无,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'RETURNING id – 2016-03-30 18:29:16

相关问题