下面的代码在 python2 中使用 MySQLDB 完美运行,如何使其与 Python3 兼容?
我已经调试并搜索了类似的问题。
错误: 在以下位置忽略异常:> 回溯(最近一次调用):文件>>> "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py",第 41 行,在 del File> "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py",第 47 行,关闭 引用错误:弱引用对象不再存在 –
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")
尝试在 db 操作完成之前做一些选择:
cursor.close()
connection.close()