可直接套用的连接mysql脚本,需要在同一目录底下先建好config档
# -*- coding:utf-8 -*-
import pymysql
import configparser
import logging
import os
import pandas as import pd
class common():
config = None
db = None
def run(self):
self.init()
self.query()
def init(self):
self.config = configparser.RawConfigParser()
self.config.read(r'./config.cfg')
if not os.path.exists('./Log'):
os.makedirs('./Log')
logging.basicConfig(filename = './Log/'+datetime.datetime.today().strftime("%Y%m%d")+'.log'
, level = logging.INFO
, format = '%(asctime)s %(message)s'
, datefmt = '%Y/%m%d %T:%M:%S:%p')
self.db = pymysql.connect((host = commonObj.config.get('Mysql_db','host')
, port = int(commonObj.config.get('Mysql_db','port'))
, user = commonObj.config.get('Mysql_db','user')
, password = commonObj.config.get('Mysql_db','password')
, database = commonObj.config.get('Mysql_db','database'),charset = 'utf8')
def query(self):
SQL = """SELECT * FROM `HelloWorld`;"""
try:
#with语句打开建游标,可以不用写关闭游标语句cursor.close()
with self.db.cursor() as Cur:
list_col = []
Cur.execute(SQL)
#打印结果,fetchall()返回多行
result = Cur.fetchall()
desc = Cur.description
#给结果DataFrame加上栏位名
[list_col.append(field[0]) for field in desc]
result.columns = list_col
except Exception as e:
#错误信息记录到日志中
logging.error(e)
finally:
#必须要关闭连接
self.db.close()
print(result)
if __name__ == '__main__':
#类的实例化
t = common()
t.run()
蟹蟹
网友评论