Reputation: 13
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:
Assigning individual cur.close() and db.commit() as per the examples here, didn't work either. (Side question: Should I be closing/committing them individually nevertheless? Is that a general good practice or context-based?)
Using a cur.rowcount method for Step 2 as well as I thought maybe the problem was on the SQL side but, the problem still persists.
Did a search on SO and couldn't find any similar case.
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
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