0
votes

Below code works perfectly in python2 with MySQLDB, how can I make it Python3 compatible?

I have debugged and searched for similar questions.

Error: Exception ignored in: > Traceback (most recent call last): File > > > "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 41, in del File > "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 47, in close ReferenceError: weakly-referenced object no longer exists –

class Database():

    def __init__(self):
        self.host = 'localhost'
        self.user = 'user'
        self.password = 'pwd'  
        self.db = 'dbname'
        self.connection = pymysql.connect(host=self.host, user=self.user, passwd=self.password, db=self.db,use_unicode=True, charset="utf8")
        self.cursor = self.connection.cursor()

    def storeToDB(self,ID,string,g,e):
        import datetime

        curr_time = datetime.datetime.now()
        status = 0
        try:
            self.cursor.execute("""INSERT INTO master_data (`job_id`,`sstring`,`grl`,`erl`,`status`,`insert_timestamp`) \
            VALUES (%s,%s,%s,%s,%s,%s)""",(jobID,search_string,g,e,status,curr_time))
            self.connection.commit()
        except:
            self.connection.rollback()
if __name__ == "__main__":
    db = Database()
    db.storeToDB(20,"hello","something.com","e.com")
1
Your example code would not even compile. Please show the exact code, or obscure the local variables correctly. - karthikr
but it's interpreted... :) - inbinder
Well. Your code catches all exceptions and then ignores them. Check out how it's done in the pymysql's documentation instead. Use a context manager (with connection.cursor() as cursor:) and try-finally instead of try-except-(pretend error didn't happen) pymysql.readthedocs.io/en/latest/user/examples.html - Håken Lid
Make sure that you have the latest version of PyMySQL (0.7.4). It seems like your version doesn't implement the context manager interfaces. - Håken Lid
Thanks @HåkenLid, it worked perfectly :) - neo

1 Answers

0
votes

Try to do some opt before db operation finish :

cursor.close()
connection.close()