在python3.x中连接mysql数据库要先安装一下pymysql:
在pycharm中 File->Settings->Project->Project Interpreter
简单测试了一下查询mysql自带的 information_schema数据库
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# @author:TalentC
# @Time:2018/10/19
import pymysql.cursors
class mysql(object):
def __init__(self,dbinfo):
try:
# connect to database
self.connect = pymysql.Connect(
host=dbinfo['host'],
port=dbinfo['port'],
user=dbinfo['user'],
passwd=dbinfo['passwd'],
db=dbinfo['db'],
charset=dbinfo['charset']
)
self.cursor = self.connect.cursor()
except Exception as e:
print(e)
def __del__(self):
self.cursor.close()
self.connect.close()
def select(self,sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def insert(self,sql):
try:
self.cursor.execute(sql)
self.connect.commit()
return self.cursor.rowcount
except Exception as e:
return e
def update(self,sql):
try:
self.cursor(sql)
self.connect.commit()
return self.cursor.rowcount
except Exception as e:
return e
def delete(self,sql):
try:
self.cursor(sql)
self.connect.commit()
return self.cursor.rowcount
except Exception as e:
return e
def rollback(self):
self.connect.rollback()
if __name__ == '__main__':
dbinfo = {'host': '192.168.28.212',
'port': 3306,
'user': 'root',
'passwd': 'fa',
'db': 'information_schema',
'charset': 'utf8'
}
db = mysql(dbinfo)
sql = 'select * from CHARACTER_SETS'
res = db.select(sql)
for row in res:
print(row)
输出结果: