mysqldb在pycharm导入时搜索mysql-python直接导入就好用法如下
注意导出的数据格式,可以用json转换
class mysqlDB():
def __init__(self, host, port, passwd, db, user, charset='utf8'):
self.host = host
self.port = port
self.user = user
self.db = db
self.passwd = passwd
self.con = MySQLdb.connect(self.host, self.user, self.passwd, self.db)
self.cur = self.con.cursor()
def close(self):
self.con.close()
self.cur.close()
def select(self, sql):
self.cur.execute(sql)
data = self.cur.fetchall()
self.con.commit()
self.close()
return data
def insert(self, sql):
self.cur.execute(sql)
self.con.commit()
self.close()
Mysql = mysqlDB(host, port, passwd, db, user)
data = Mysql.select(sql) #查询
Mysql.insert(sql) #插入和修改
#格式转换
data = json.dumps(data, encoding='utf-8', ensure_ascii=False)