python3封装pymysql,方便快速调用

本文介绍了如何对pymysql进行简单的二次封装,以便更方便快捷地进行MySQL数据库的操作。通过导入封装后的模块并连接数据库,可以轻松执行select、update、insert、delete等操作。
摘要由CSDN通过智能技术生成

介绍

这是通过对pymysql进行的二次简单封装,封装后可以很方便地调用以对mysql数据库进行操作。
引用方式:在要使用数据库的地方import该对象,然后通过AmanMySQL(mysql[“host”], mysql[“user”], mysql[“passwd”], mysql[“dbName”])连接数据库赋值给某一变量,之后就可以通过对应变量对select、update、insert、delete等对数据库做操作。源码和示例如下:

源码

#encoding: utf-8

import pymysql

class AmanMySQL():
    # 初始化
    def __init__(self, host, user, passwd, dbName):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.dbName = dbName
    
    # 连接数据库,需要传数据库地址、用户名、密码、数据库名称,默认设置了编码信息
    def connet(self):
        try:
            self.db = pymysql.connect(self.host, self.user, self.passwd, self.dbName, use_unicode=True, charset='utf8')
            self.cursor = self.db.cursor()
        except Exception as e:
            return e
    
     # 关闭数据库连接 
    def close(self):
        try:
            self.cursor.close()
            self.db.close()
        except Exception as e:
            return e

     # 查询操作,查询单条数据
    def get_one(self, sql):
        # res = None
        try:
            self.connet()
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
            self.close()
        except Exception:
            res = None
        return res

     # 查询操作,查询多条数据
    def get_all(self, sql):
        # res = ()
        try:
            self.connet()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            self.close()
        except Exception:
            res = ()
        return res
   
     # 查询数据库对象
    def get_all_obj(self, sql, tableName, *args):
        resList = []
        fieldsList = []
        try:
            if (len(args) > 0):
                for item in args:
                    fieldsList.append(item)
            else:
                fieldsSql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '%s' and table_schema = '%s'" % (
                    tableName, self.dbName)
                fields = self.get_all(fieldsSql)
                for item in fields:
                    fieldsList.append(item[0
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值