美文网首页
pymysql 封装

pymysql 封装

作者: 灰太狼256 | 来源:发表于2021-02-06 23:30 被阅读0次
import pymysql,time,datetime

class MysqlHandle(object):

    def __init__(self,host,username,password,database):
        self.host = host
        self.username = username
        self.password = password
        self.database = database
        self.con = pymysql.connect(self.host,self.username,self.password,self.database,charset='utf8')

    def insert(self,sql):
        self.cursor = self.con.cursor()

        try:
            data = self.cursor.execute(sql)
            self.con.commit()
            
            return data
        except:
            self.con.rollback()
        finally:
            self.close()
            
    def delete(self,sql):
        self.cursor = self.con.cursor()

        try:
            data = self.cursor.execute(sql)
            self.con.commit()
            
            return data
        except:
            self.con.rollback()
        finally:
            self.close()

    def update(self,sql):
        self.cursor = self.con.cursor()

        try:
            data =self.cursor.execute(sql)
            self.con.commit()
            
            return data
        except:
            self.con.rollback()
        finally:
            self.close()

    def select(self,sql,one=True):
        self.cursor = self.con.cursor()
        try:
            self.cursor.execute(sql)
            if one:
                return self.cursor.fetchone()
            else:
                return self.cursor.fetchall()
                
            self.close()
        except:
            print('Error: unable to fecth data')
        finally:
            self.close()

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

MysqlHost = 'localhost'
MysqlUsername = 'root'
MysqlPassword = '123456789'
MysqlDatabase = 'demo'

con = MysqlHandle(MysqlHost,MysqlUsername,MysqlPassword,MysqlDatabase)

def insert():
    dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    create_time = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
    data = con.insert("INSERT INTO user(email,password,create_time)VALUES('%s','%s','%s')" % ('123456@qq.com','123456',create_time))
    print(data)
insert()

def delete():
    data = con.delete("DELETE from user WHERE email = '%s'" % ('123456@qq.com'))
    print(data)
# delete()

def update():
    dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    last_login_time = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
    data = con.update("UPDATE user set last_login_time = '%s' WHERE email = '%s'" %(last_login_time,'123456@qq.com'))
    print(data)  
# update()

def select():
    data = con.select("SELECT * FROM user WHERE email = '%s'" %('123456@qq.com'),one=True)
    print(data)
# select()

相关文章

网友评论

      本文标题:pymysql 封装

      本文链接:https://www.haomeiwen.com/subject/mjsatltx.html