码迷,mamicode.com
首页 > 数据库 > 详细

python之MySQL学习——简单的增删改查封装

时间:2017-07-06 16:51:10      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:错误   database   ams   nbsp   close   insert   .exe   llb   ase   

1.增删改查封装类MysqlHelper.py

 1 import pymysql as ps
 2 
 3 class MysqlHelper:
 4     def __init__(self, host, user, password, database, charset):
 5         self.host = host
 6         self.user = user
 7         self.password = password
 8         self.database = database
 9         self.charset = charset
10         self.db = None
11         self.curs = None
12     # 数据库连接
13     def open(self):
14         self.db = ps.connect(host=self.host, user=self.user, password=self.password,database=self.database, charset=self.charset)
15         self.curs = self.db.cursor()
16     # 数据库关闭
17     def close(self):
18         self.curs.close()
19         self.db.close()
20     # 数据增删改
21     def cud(self, sql, params):
22         self.open()
23         try:
24             self.curs.execute(sql, params)
25             self.db.commit()
26             print("ok")
27         except :
28             print(cud出现错误)
29             self.db.rollback()
30         self.close()
31     # 数据查询
32     def find(self, sql, params):
33         self.open()
34         try:
35             result = self.curs.execute(sql, params)
36             self.close()
37             print("ok")
38             return result
39         except:
40             print(find出现错误)

2.数据查询(引入封装类)

1 from MysqlHelper import MysqlHelper
2 
3 mh = MysqlHelper(localhost, root, 123456, test, utf8)
4 sql = "select * from user where name=%s"
5 print(mh.find(sql, 小明))

3.数据修改(引入封装类)

1 from MysqlHelper import MysqlHelper
2 
3 mh = MysqlHelper(localhost, root, 123456, test, utf8)
4 sql = "insert into user(name,password) values(%s,%s)"
5 mh.cud(sql, (小光, 123456))

 

python之MySQL学习——简单的增删改查封装

标签:错误   database   ams   nbsp   close   insert   .exe   llb   ase   

原文地址:http://www.cnblogs.com/xiaomingzaixian/p/7126869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!