Query the Universe
Query the Universe

Reputation: 13

2 Try / Except statement doesn't work in normal order but works when codes are flipped

Good day guys, I hope to get a little advice on this. I can't seem to get this 2 TRY/EXCEPT statement to run in the order I want them to. They however, work great if I put STEP2 first then STEP1.

This current code prints out only.

Transferred: x rows.

If flipped, they print both.

Unfetched: x rows.
Transferred: x rows.

I tried:

Running on Python 2.7. Code:

import MySQLdb
import os

#Initiate connection to database.
db = MySQLdb.connect(host="localhost",user="AAA",passwd="LETMEINYO",db="sandbox")
cur = db.cursor()

#Declare variables.
viewvalue = "1"

mainreplace =   (
                    "INSERT INTO datalog "
                    "SELECT * FROM cachelog WHERE viewcount = %s; "
                    "DELETE FROM cachelog WHERE viewcount = %s; "
                    % (viewvalue, viewvalue)
                )

balance =   (
                "SELECT COUNT(*) FROM cachelog "
                "WHERE viewcount > 1"
            )

#STEP 1: Copy and delete old data then print results.
try:
    cur.execute(mainreplace)
    transferred = cur.rowcount
    print "Transferred: %s rows." %(transferred)
except:
    pass

#STEP 2: Check for unfetched data and print results.
try:
    cur.execute(balance)
    unfetched = cur.fetchone()
    print "Unfetched: %s rows." % (unfetched)
except:
    pass

#Confirm and close connection.
cur.close()
db.commit()
db.close()

Pardon any of my un-Pythonic ways as I am still very much a beginner. Any advice is much appreciated, thank you!

Upvotes: 0

Views: 70

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

You have two blaring un-Pythonic bits of code: the use of a bare except: without saying which exception you want to catch, and using pass in that except block so the exception is entirely ignored!

The problem with code like that is that if something goes wrong, you'll never see the error message, so you can't find out what's wrong.

The problem is perhaps that your "mainreplace" query deletes everything from the "cachelog" table, so the "balance" query after it has no rows, so fetchone() fails, throws an exception and the line after it is never executed. Or maybe something completely different, hard to tell from here.

If you didn't have that try/except there, you would have had a nice error message and you wouldn't have had to ask this question.

Upvotes: 1

Related Questions