最开始用python连接mysql的时候,会经常性的连一次关一次,如此重复,导致端口可能会占用从而报错,后面采用一次性连接的方式
代码如下:
import pymysqlimport WriteLogimport config DATABASE_INFO = config.DATABASE_INFO SQL = config.SQLclass GetData(): def __init__(self): self.conn, self.cur = self.connect_db() def connect_db(self): try: conn = pymysql.connect(**DATABASE_INFO) cur = conn.cursor() return conn, cur except Exception as e: WriteLog.writeLog('dbError',str(e)) return None def get_data(self): self.cur.execute(SQL) self.conn.commit() # self.cur.close() 这两行就不要在写了 # self.conn.close() pass
下面是自定义LOG的代码:
# -*- coding: UTF-8 -*-import timeimport osimport config LOG_PATH = config.LOG_PATHclass WriteLog(object): @staticmethod def writeLog(file,logs): if not os.path.exists(LOG_PATH): os.mkdir(LOG_PATH) with open(LOG_PATH + '\\'+file+'.log', "a") as f: str1 = WriteLog.localTime() f.write(str1 + ' ' + logs + "\n") @staticmethod def localTime(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
作者:停泊泊泊泊泊泊
链接:https://www.jianshu.com/p/5f312f0915e1
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦