python封装mysql

本文介绍了一个使用Python和pymysql模块进行数据库操作的示例,包括连接数据库、执行查询、获取单条或多条记录、执行插入、更新和删除操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pymysql

class DBHelper():
    def __init__(self,host, user, passwd, dbName):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.dbName = dbName
    def connet(self):
        #连接到数据库
        self.db = pymysql.connect(self.host,self.user,self.passwd,self.dbName)
        #创建游标
        self.cursor = self.db.cursor()
        
    def close(self):
        self.cursor.close()
        self.db.close()
    
    #查询一条数据
    def get_one(self, sql):
        res = None
        try:
            self.connet()
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
            self.close()
        except:
            print("查询失败")
        return res
    
    #得到所有的数据
    def get_all(self, sql):
        res = ()
        try:
            self.connet()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            self.close()
        except:
            print("查询失败")
        return res


    #插入
    def insert(self, sql):
        return self.__edit(sql)
    
    #更新
    def update(self, sql):
        return self.__edit(sql)
    
    #删除
    def delete(self, sql):
        return self.__edit(sql)

    def __edit(self,sql):
        count = 0
        try:
            self.connet()
            count = self.cursor.execute(sql)
            self.db.commit()
            self.close()
        except:
            print("事物提交失败")
            self.db.rollback()
        return count
if __name__ == '__main__':
    dbh = DbHelper(host='localhost',username='root',password='123456',database='stu')
    #查询当前用户
    #res = dbh.get_one('select user()')
    #res = dbh.insert_data("insert into student values(0,'谭松韵',29,0,99)")
    #res = dbh.get_all('select * from student')
    #res = dbh.update_data("update student set name='周杰伦' where id=4")
    res = dbh.delete_data("delete from student where id>60")
    print(res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值