51

NULL変数がNonePythonにある場合、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、値が の場合、データベースに を挿入するにはどうすればよいですか?Nonepsycopg2

4

4 に答える 4

66

データベースに null 値を挿入するには、次の 2 つのオプションがあります。

  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))
于 2010-11-20T06:59:29.043 に答える
1

これが私の解決策です:

text = '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))

text = text.replace("nan", "null")

mycursor.execute(text)
于 2021-02-10T23:57:09.893 に答える