最开始用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文件中作为配置