py3不支持MySQLdb,需要导入pymysql模块
# coding: utf-8
# Team : Quality Management Center
# Author:Carson
# Date :2019/6/20 17:52
# Tool :PyCharm import pymysql class MysqldbHelper(object): def __init__(self, host='数据库地址', username='登录名', password='密码', port='端口', database='库名称', charset='utf8'):
self.host = host
self.username = username
self.password = password
self.database = database
self.port = port
self.con = None
self.cur = None
self.charset = charset
try:
self.con = pymysql.connect(host=self.host, user=self.username, passwd=self.password, port=self.port, db=self.database)
# 所有的查询,都在连接 con 的一个模块 cursor 上面运行的
self.cur = self.con.cursor()
except:
print("DataBase connect error,please check the db config.") def execute(self, sql): sql = sql
try:
self.cur.execute(sql)
results = self.cur.fetchall()
print(results)
self.cur.close()
except pymysql.Error as e:
error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])
print(error)