Python3.0 操作MySQL数据库执行SQL语句

py3不支持MySQLdb,需要导入pymysql模块
 1 # coding: utf-8
 2 # Team : Quality Management Center
 3 # Author:Carson
 4 # Date :2019/6/20 17:52
 5 # Tool :PyCharm
 6 
 7 import pymysql
 8 
 9 
10 class MysqldbHelper(object):
11 
12     def __init__(self, host='数据库地址', username='登录名', password='密码', port='端口',  database='库名称', charset='utf8'):
13         self.host = host
14         self.username = username
15         self.password = password
16         self.database = database
17         self.port = port
18         self.con = None
19         self.cur = None
20         self.charset = charset
21         try:
22             self.con = pymysql.connect(host=self.host, user=self.username, passwd=self.password, port=self.port, db=self.database)
23             # 所有的查询,都在连接 con 的一个模块 cursor 上面运行的
24             self.cur = self.con.cursor()
25         except:
26             print("DataBase connect error,please check the db config.")
27 
28     def execute(self, sql):
29 
30         sql = sql
31         try:
32             self.cur.execute(sql)
33             results = self.cur.fetchall()
34             print(results)
35             self.cur.close()
36         except pymysql.Error as e:
37             error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])
38             print(error)
 
posted on 2019-06-11 18:28  凌风子  阅读(3138)  评论(0编辑  收藏  举报