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

Discussion in 'Python' started by fyleow, Jun 14, 2006.

  1. fyleow

    fyleow Guest

    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.
    fyleow, Jun 14, 2006
    #1
    1. Advertising

  2. fyleow

    Ben Finney Guest

    "fyleow" <> writes:

    > 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.

    --
    \ "A lot of people are afraid of heights. Not me, I'm afraid of |
    `\ widths." -- Steven Wright |
    _o__) |
    Ben Finney
    Ben Finney, Jun 14, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Phil Johnson
    Replies:
    2
    Views:
    1,195
    Phil Johnson
    Mar 7, 2008
  2. yawnmoth
    Replies:
    97
    Views:
    4,635
    Bent C Dalager
    Feb 27, 2009
  3. Rob Meade
    Replies:
    6
    Views:
    254
    Rob Meade
    Mar 1, 2004
  4. Nick Snels
    Replies:
    0
    Views:
    99
    Nick Snels
    Jan 25, 2006
  5. maya
    Replies:
    0
    Views:
    86
Loading...

Share This Page