美文网首页我爱编程
python连接mysql与自定义日志

python连接mysql与自定义日志

作者: 停泊泊泊泊泊泊 | 来源:发表于2018-08-09 15:03 被阅读0次

最开始用python连接mysql的时候,会经常性的连一次关一次,如此重复,导致端口可能会占用从而报错,后面采用一次性连接的方式

代码如下:

import pymysql
import WriteLog
import config

DATABASE_INFO = config.DATABASE_INFO
SQL = config.SQL

class 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 time
import os
import config

LOG_PATH = config.LOG_PATH

class 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())

当然所有的sql语句和连接都可以放在另外一个config文件中作为配置

相关文章

网友评论

    本文标题:python连接mysql与自定义日志

    本文链接:https://www.haomeiwen.com/subject/sftcbftx.html