Python 3.把对数据库的操作封装成一个类

 Python 3.把对数据库的操作封装成一个类:

#把对数据库的操作封装成一个类
import pymysql

class DBUtil:
    _db =None
    #在这里配置自己的SQL服务器
    _config = {
        'host':"localhost",
        'port':3306,
        'username':"root",
        'password':'123456',
        'database':"air",
        'charset':"utf-8"
    }

    def __connect(self):
        if(self._db == None):
            self._db = pymysql.connect(
                host = self._config['host'],
                port = self._config['port'],
                user = self._config['username'],
                passwd = self._config['password'],
                db = self._config['database'],
                charset = self._config['charset']
            )
        return self._db

    def __init__(self):
        self.__connect()

    def __del__(self):
        if(self._db is not None):
            self._db.close()

    def query(self,_sql):
        cursor = self.__connect().cursor()
        try:
            cursor.execute(_sql)
            data = cursor.fetchall()
            #提交到数据库执行
            self.__connect().commit()
        except:
            #如果发生错误则回滚
            self.__connect().rollback()
            return False
        return data

    def query_dic(self,_sql_dic):
        if('select' in _sql_dic.keys()):
            sql = "SELECT"+_sql_dic['select']+"FROM"+_sql_dic['from']+self.where(_sql_dic['where'])
            print(sql)
            return self.query(sql)
        elif('insert' in _sql_dic.keys()):
            sql = "INSERT INTO"+_sql_dic['insert']+self.quote(_sql_dic['domain_array'],type_filter=False+"VALUES"+self.quote(_sql_dic['value_array']))
            print(sql)
            return self.query(sql)
        if('delete' in _sql_dic.keys()):
            sql = "DELETE FROM"+_sql_dic['delete']+self.where(_sql_dic['where'])
            print(sql)
            return self.query(sql)

        def where(self,_sql):
            if(isinstance(_sql,dict)==False):
                return "WHERE"+ str(_sql)
            if(isinstance(_sql,dict)):
                _sql_dic = _sql
                s = "WHERE"
                index = 0
                for domain in _sql_dic:
                    if(index == 0):
                        s += domain + "=" + str(_sql_dic[domain]) + " "
                        index += 1
                    else:
                        s += "ADD" + domain + "=" + str(_sql_dic[domain]) + " "
                return s

        #为数组加上外括号,并拼接字符串
        def quote(self,_data_array,type_filter=True):
            s = "("
            index = 0
            if(type_filter):
                for domain in _data_array:
                    if(index == 0):
                        if(isinstance(domain,int)):
                            s += str(domain)
                        elif (isinstance(domain,str)):
                            s += "'" + domain + "'"
                        index += 1
                    else:
                        if(isinstance(domain,int)):
                            s += "," + str(domain)
                        elif(isinstance(domain,str)):
                            s += "," + "'" +domain +"'"
            else:
                for domain in _data_array:
                    if(index == 0):
                        s += str(domain)
                        index+=1
                    else:
                        s += "," + domain
            return s+")"

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值