首页 > 数据库技术 > 详细

封装一个基于MySQLdb的操作类

时间:2018-11-14 23:41:42      阅读:159      评论:0      收藏:0      [点我收藏+]
‘‘‘
下载并安装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)

 

封装一个基于MySQLdb的操作类

原文:https://www.cnblogs.com/wuxiaoshi/p/9961048.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!