I am working on PostgreSQL and psycopg2. Trying to get feed data which is updated every after 10 mins and keep this feeds contents in PostgreSQL database.My target is to retrieve and print those data from that table. But facing problem as duplicate data is also stored in the database every time I run that script due to insertion operation on table.
To get out off this problem ,I made primary key constraint of column location_title
in table Locations-musiq1
where I intend to store my feed data.But facing error.
Here is my code:
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()
My error after changing "locations_musiq1" tables column "location_title" as primary key is:
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"
Can anybody have any idea to get out of this problem ?..Thanks in advance..