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'))