python封装MySQL操作

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操作

上一篇:MySQL 查看数据库以及对表的增删改查


下一篇:mongoDB服务器连接不上Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: