首页 > 数据库技术 > 详细

python封装MySQL操作

时间:2020-11-16 19:49:20      阅读:42      评论:0      收藏:0      [点我收藏+]

import pymysql

class MysqlHelper():
def init(self,host,port,db,user,passwd,charset=‘utf8‘):
self.host = host
self.port=port
self.db=db
self.user=user
self.passwd=passwd
self.charset=charset

def connect(self):
    self.conn=pymysql.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
    self.cursor=self.conn.cursor()

def close(self):
    self.cursor.close()
    self.conn.close()

def get_all(self,sql):
    res = ()
    try:
        self.connect()
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
    except Exception as e:
        print(e)
    return res

def insert(self,sql):
    try:
        self.connect()
        self.cursor.execute(sql)
        self.conn.commit()
    except Exception as e:
        self.conn.rollback()
        print(e)

def update(self,sql):
    try:
        self.connect()
        self.cursor.execute(sql)
        self.conn.commit()
    except Exception as e:
        self.conn.rollback()
        print(e)

def delete(self,sql):
    try:
        self.connect()
        self.cursor.execute(sql)
        self.conn.commit()
    except Exception as e:
        self.conn.rollback()
        print(e)

python封装MySQL操作

原文:https://www.cnblogs.com/mysweets/p/13986049.html

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