如果数据库中存在artist
,我如何将这些does not
插入数据库。我写了以下代码。但这是错误的。你能帮帮我吗?感谢
艺术家名单
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;
更新:
我已经在列名上添加了约束来强制列是唯一的。
答案 0 :(得分:2)
在数据库端强制执行该操作。在列名称上添加约束以强制列是唯一的。这应该足够了:
ALTER TABLE song_artist ADD UNIQUE(name);
通过这种方式,您可以确定无论您做什么,都不会有任何重复的值。
您可以使用以下查询插入数据:
INSERT INTO song_artist(name,slug)
选择'Mahendra Kapoor','mahendra-kapoor'
什么不存在
(
选择42
来自song_artist
名字='Mahendra Kapoor'
);
答案 1 :(得分:0)
您可以添加Szymon Guz建议的唯一约束,
ALTER TABLE song_artist ADD UNIQUE (name);
然后使用try / except来处理重复错误:
try:
cursor.execute( 'INSERT INTO song_artist (name,slug) VALUES (%s,%s) RETURNING id;',(artist[0],artist_slug))
except psycopg2.IntegrityError:
debug.print 'Duplicate values found. Insert was not successful'
答案 2 :(得分:0)
你必须使用if not artist_rows:
这就是全部
artist_slug = self.makeSlug(l)
cursor.execute("SELECT count(id) FROM song_artist WHERE name = %s and slug = %s ;" ,(l,artist_slug) ) # Id exist?
artist_rows = cursor.fetchone()
#artist_rows = artist_rows[0]
db.commit()
if not artist_rows:
cursor.execute( 'INSERT INTO song_artist (name,slug) VALUES (%s,%s) RETURNING id;',(l,artist_slug))
#k=( 'INSERT INTO song_artist (name,slug) SELECT %s,%s WHERE NOT EXISTS ( SELECT 42 FROM song_artist WHERE name = %s) RETURNING id;'%(l,artist_slug,l))
artist_id = cursor.fetchone()[0] # get mysql_insert_id using RETURNING
db.commit()