質問

ある良い練習に入る NULL キー値をデータベースをPostgreSQLの場合変数 None Python?

このクエリ:

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.

ですが、どのような NULL を挿入することをデータベースの値が None, を使用し、 psycopg2 ドライバー?

役に立ちましたか?

解決

挿入するnull値をデータベースにおいて二つのオプション:

  1. を省略できる分野からのINSERTステートメント、または
  2. 使用 None

また:防SQL-injectionを使ってはいけません通常の文字列補間のためのご質問.

した場合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))

他のヒント

現在のpsycopgでは、代わりなしの、 '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)

また、列の数が多いと実用的で簡単な方法:

rowNoneを含有してもよいことが、挿入される値のリストとします。

を次のようにPostgreSQLの中にそれを挿入するには、我々はやります
values = ','.join(["'" + str(i) + "'" if i else 'NULL' for i in row])
cursor.execute('insert into myTable VALUES ({});'.format(values))
conn.commit()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top