gpt4 book ai didi

python - 在 Python 中避免 PostgreSQL 数据库中的重复数据

转载 作者:行者123 更新时间:2023-11-28 22:07:14 25 4
gpt4 key购买 nike

我正在研究 PostgreSQL 和 psycopg2。试获取每 10 分钟更新一次的提要数据并将此提要内容保存在 PostgreSQL 数据库中。我的目标是检索并从该表中打印这些数据。但是由于对表的插入操作,每次我运行该脚本时,重复数据也会存储在数据库中。

为了解决这个问题,我在表 Locations-musiq1 中对列 location_title 进行了主键约束,我打算在其中存储我的提要数据。但面临错误。

这是我的代码:

import psycopg2
import sys
import feedparser
import codecs
import psycopg2.extensions


# Parsing data from Geofeed location feeds

data = feedparser.parse("some URL")
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)



try:

conn=psycopg2.connect("dbname='name' user='postgres' host='localhost' password='abcds'")
conn.set_client_encoding('UNICODE')


except:
print "I am unable to connect to the database, exiting."
sys.exit()
cur=conn.cursor()


for i in range(len(data['entries'])):
cur.execute("INSERT INTO locations_musiq1(location, location_title) VALUES (%s, %s)", (data.entries[i].title,data.entries[i].summary))
conn.commit()
cur.execute("SELECT * FROM locations_musiq1;")
cur.fetchone()
for row in cur:
print ' '.join(row[1:])


cur.close()
conn.close()

将“locations_musiq1”表列“location_title”更改为主键后我的错误是:

    Traceback (most recent call last):      File "F:\JavaWorkspace\Test\src\postgr_example.py", line 28, in         cur.execute("INSERT INTO locations_musiq1(location, location_title) VALUES (%s, %s)",    (data.entries[i].title,data.entries[i].summary))    psycopg2.IntegrityError: duplicate key value violates unique constraint "locations_musiq1_pkey"

任何人都可以解决这个问题吗?..提前致谢..

最佳答案

你可以尝试这样的事情:

cur.execute("""
INSERT INTO locations_musiq1(location, location_title)
SELECT %s, %s WHERE NOT EXISTS
(SELECT location_title FROM locations_musiq1 WHERE location_title=%s);
""", (data.entries[i].title, data.entries[i].summary, data.entries[i].summary))

关于python - 在 Python 中避免 PostgreSQL 数据库中的重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2415884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com