‘‘‘ 下载并安装MySQLdb模块 链接地址 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient ‘‘‘
我的环境是 python3.6 windows10 64位机器,所以下载(点击)
下载完毕后,运行 pip install mysqlclient?1.3.13?cp36?cp36m?win_amd64.whl
下面就准备开始我们的封装类
#-*- coding=utf-8 -*- import MySQLdb from MySQLdb import cursors import random class PMySQL(): #初始化,链接数据库并设置出字符集,并且获取游标 def __init__(self): try: self.db = MySQLdb.connect(‘localhost‘,‘root‘,‘root‘,‘test‘,cursorclass=cursors.DictCursor,charset=‘utf8‘) if self.db is not None: self.cursor = self.db.cursor() except Exception as e: self.cursor = ‘‘ #查询方法 def select(self,sql): data_list = [] try: self.cursor.execute(sql) self.db.commit() data = self.cursor.fetchall() if data is not None: for i in data: data_list.append(i) return data_list except Exception as e: return data_list #插入方法 def insert(self,sql): try: self.cursor.execute(sql) self.db.commit() return self.cursor.lastrowid except Exception as e: self.db.rollback() return 0 #更新方法 def update(self,sql): try: self.cursor.execute(sql) self.db.commit() return self.cursor.rowcount except Exception as e: self.db.rollback() return 0 #删除方法 def delete(self,sql): try: self.cursor.execute(sql) self.db.commit() return self.cursor.rowcount() except Exception as e: self.db.rollback() return 0 if __name__ == ‘__main__‘: # 1 链接数据库,并设置字符集 # db = MySQLdb.connect(‘localhost‘,‘root‘,‘root‘,‘test‘,cursorclass=cursors.DictCursor,charset=‘utf8‘) # print(db) # 2 获取游标 # cursor = db.cursor() # print(cursor) # 3 准备sql语句 # sql = ‘select CONTINENT,COUNTRY,CODE from nation limit 10‘ # sql = ‘insert into user(`name`) values("zhangsan")‘ # sql = "update user set name=‘lisi‘ where id=4" # sql = "delete from user where id=4" # 4 执行 # cursor.execute(sql) # 查询 # data = cursor.fetchall() #插入 # db.commit() # print(data) # 5 处理数据 # T = [] # if data is not None: # for i in data: # T.append(i) # print(T) # print(cursor.rowcount) # 6 释放资源,关闭链接 # db.close() p = PMySQL() sql = "delete from user where id=4" data = p.delete(sql) print(data)
原文:https://www.cnblogs.com/wuxiaoshi/p/9961048.html