只有在數據庫中存在does not
時,我如何將這些artist
插入到數據庫中。我寫了下面的代碼。但這是錯誤的。你能幫我嗎?感謝避免重複數據PostgreSQL
藝術家名單
Lata Mangeshkar
Lata Mangeshkar
Lata Mangeshkar
Asha Bhosle
Lata Mangeshkar
Mahendra Kapoor
Lata Mangeshkar
Kishore Kumar
Lata Mangeshkar
我的代碼
for l in artist:
l = l.strip()
cursor.execute("SELECT id FROM song_artist WHERE name = %s ;" ,(l,)) # Id exist?
artist_rows = cursor.fetchone()
if not artist_rows:
artist_slug = self.makeSlug(artist[0])
cursor.execute('INSERT INTO song_artist (name,slug) VALUES (%s,%s) RETURNING id;',(artist[0],artist_slug))
print k
輸出:
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Asha Bhosle,asha-bhosle) RETURNING i
d;
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Mahendra Kapoor,mahendra-kapoor) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Mahendra Kapoor,mahendra-kapoor) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
輸出應爲:
INSERT INTO song_artist (name,slug) VALUES (Asha Bhosle,asha-bhosle) RETURNING i
d;
INSERT INTO song_artist (name,slug) VALUES (Lata Mangeshkar,lata-mangeshkar) RET
URNING id;
INSERT INTO song_artist (name,slug) VALUES (Mahendra Kapoor,mahendra-kapoor) RET
URNING id;
更新:
我已經添加了對列名的約束來強制該列是唯一的。
這是com折襞。什麼是42? – Kulbir
我試過你的代碼。但不工作。獲取錯誤消息。 'psycopg2.IntegrityError:重複鍵值違反唯一約束「song_ar tist_slug_key」 詳細信息:鍵(slug)=(lata-mangeshkar)已存在。「# – Kulbir
這是因爲您已經有重複的數據。刪除重複項並重試。 –