python连接mysql数据库封装

源码:

 1 import pymysql
 2 
 3 class MysqlConnect(object):
 4     # 魔术方法, 初始化, 构造函数
 5     def __init__(self, host, user, password, database):
 6         '''
 7 
 8         :param host: IP
 9         :param user: 用户名
10         :param password: 密码
11         :param port: 端口号
12         :param database: 数据库名
13         :param charset: 编码格式
14         '''
15         self.db = pymysql.connect(host=host, user=user, password=password,port=3306, database=database, charset='utf8')
16         self.cursor = self.db.cursor()
17 
18     # 将要插入的数据写成元组传入
19     def exec_data(self, sql, data=None):
20         # 执行SQL语句
21         self.cursor.execute(sql, data)
22         # 提交到数据库执行
23         self.db.commit()
24 
25     # sql拼接时使用repr(),将字符串原样输出
26     def exec(self, sql):
27         self.cursor.execute(sql)
28         # 提交到数据库执行
29         self.db.commit()
30 
31     def select(self,sql):
32         self.cursor.execute(sql)
33         # 获取所有记录列表
34         results = self.cursor.fetchall()
35         for row in results:
36             print(row)
37 
38     # 魔术方法, 析构化 ,析构函数
39     def __del__(self):
40         self.cursor.close()
41         self.db.close()
42 
43 if __name__ == '__main__':
44     mc = MysqlConnect('127.0.0.1', 'root', '123456', 'homework')
45     # mc.exec('insert into test(id, text) values(%s, %s)' % (1, repr('哈送到附近')))
46     mc.exec_data('insert into test(id, text) values(%s, %s)' % (1, repr('哈送到附近')))
47     # mc.exec_data('insert into test(id, text) values(%s, %s)',(13, '哈送到附近'))
48     mc.select('select * from test')

 

posted @ 2018-08-15 22:43  _积木城池  阅读(4008)  评论(0编辑  收藏  举报