どを挿入するNULLの価値観へのPostgreSQLデータベースのPython?
-
26-09-2019 - |
質問
ある良い練習に入る 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_id
は None
.
ですが、どのような NULL
を挿入することをデータベースの値が None
, を使用し、 psycopg2
ドライバー?
解決
挿入するnull値をデータベースにおいて二つのオプション:
- を省略できる分野からのINSERTステートメント、または
- 使用
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)
また、列の数が多いと実用的で簡単な方法:
row
はNone
を含有してもよいことが、挿入される値のリストとします。
values = ','.join(["'" + str(i) + "'" if i else 'NULL' for i in row])
cursor.execute('insert into myTable VALUES ({});'.format(values))
conn.commit()
所属していません StackOverflow