How do I ignore the errors thrown by the DB api?

F

fyleow

Here's the code I have in place right now.

cursor.execute("SELECT link FROM feeds_feed WHERE link=%s",
(self.link,))
db.commit()

if cursor.rowcount == 0:
cursor.execute("INSERT INTO feeds_feed (release_group,
title, link, category, pub_date) VALUES (%s, %s, %s, %s, now())",
(self.group, self.title, self.link, self.category,))
db.commit()
print "Inserting"
else:
print "Already Exists"

Basically the uniqueness of the link attribute is enforced in the
database so if I try to insert a value that already exists I get an
error that breaks the program. Right now I do a SELECT query first to
check if the value already exists. The insert is only executed only if
the value doesn't already exist.

This is a really bad way of doing things because I'm accessing the DB
way more than I need to. It would be great if I could just insert
values into the DB and let the uniqueness check at the DB level to
either add or refuse the duplicate value. I'm not really interested if
a particular value is rejected or added, I just want the most efficient
way to insert values.

I would really appreciate any suggestions or tips.

Thanks.
 
B

Ben Finney

fyleow said:
It would be great if I could just insert values into the DB and let
the uniqueness check at the DB level to either add or refuse the
duplicate value.

The Pythonic way to do this is find out what exception is generated by
the event you want to handle, and handle that exception.

record_stuff = build_new_record()
try:
insert_record(record_stuff)
except FailedToInsert, e:
handle_insert_failure(e, record_stuff)

Define each of those functions, name the actual exception class, and
you're done.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top