Python3 封装 简单的数据库操作类 连贯操作

数据库操作是编程的常用功能
我在使用其它语言的框架中,经常用到“连贯操作”.于是基于pymysql这一数据库包,造了一个易用的数据库操作类

使用方法:

1.引入代码

from DBDriver import LYDB #DBDriver.py是文件名, LYDB是类名

2.连接数据库

db = LYDB(host="192.168.1.1", port="3306", user="dbuser", password="mypassword", db="mydb")

3.查询数据

示例1

db.table("table_a").where({"c_a":"value_a","c_b":"value_b"}).order("id DESC").limit(100).find()

这个查询类等效于下面这个sql语句

 SELECT * FROM `table_a` WHERE `c_a` = "value_a" AND `c_b` = "value_b" ORDER BY `id` DESC LIMIT 100

示例2
有时候 查询条件比较复杂,这时候where里面的参数也可以是字符串

db.table("table_a").field(["c_a","c_b"]).where("`c_c` > 100 AND `name` = 'test'").find()

4.插入数据

db.table("table_a").data([{"c_a":"value1","c_b":"value2"},{"c_a":"value3","c_b":"value4"}]).insert()

5.修改数据

db.table("table_a").data({"c_a":"value1"}).where({"c_b":"value2"}).save()

6.删除数据

db.table("table_a").where({"c_a":"value1"}).delete()

7.关闭数据库连接

db.close()

以下是封装的工具的代码本体,

希望您至少点个赞,感谢

import pymysql

# 作者 刘宇LY
# 允许所有人使用,但希望注明出处
# 作者主页:https://blog.csdn.net/qq_28766327?type=blog

class LYDB:
    tableName = ""
    fieldName = " * "
    whereStr = " WHERE 1 "
    orderStr = ""
    limitStr = ""
    dataArray = []
    dataDic = {}
    cursor = None
    db = None
    lastSql = ""
    groupStr = ""

    def __init__(self, host, port, user, password, db):
        self.db,self.cursor = self.__getDBCusor(host, int(port),user, password, db)

    def resetDefaultData(self):
        self.tableName = ""
        self.fieldName = " * "
        self.whereStr = " WHERE 1 "
        self.orderStr = ""
        self.limitStr = ""
        self.groupStr = ""
        self.dataArray = []

    def __getDBCusor(self,host, port, user,password, db):
        db = pymysql.connect(host=host, port=port, user=user, password=password, database=db, autocommit=True,cursorclass=pymysql.cursors.DictCursor)
        cursor = db.cursor()
        return db, cursor

    def table(self,tableName):
        self.tableName = tableName
        return self

    def field(self,field):
        if isinstance(field,str):
            self.fieldName = field
        if isinstance(field,list):
            self.fieldName = "`"+ "`,`".join(field) + "`"
        return self

    def data(self,dataArray):
        if isinstance(dataArray,dict):
            self.dataDic = dataArray
        elif isinstance(dataArray,list):
            self.dataArray = dataArray
        return self

    def where(self,whereData):
        if isinstance(whereData,str):
            self.whereStr = " WHERE "+ whereData
        if isinstance(whereData,dict):
            tmpWhereArray = []
            for key in whereData:
                value = str(whereData[key])
                value = value.replace("\\","\\\\")
                value = value.replace("'","\\'")
                tmpWhere = "`"+str(key) + "` = '"+value+"'"
                tmpWhereArray.append(tmpWhere)
            self.whereStr = " WHERE "+" AND ".join(tmpWhereArray)
        return self

    def order(self,orderStr):
        self.orderStr = " ORDER BY "+str(orderStr)
        return self

    def group(self,group):
        self.groupStr = " GROUP BY "+group

    def limit(self,limitStr):
        self.limitStr = " LIMIT "+str(limitStr)
        return self

    def insert(self,onDuplicateKey=""):
        data0 = self.dataArray[0]
        keyArray = data0.keys()
        keyString = "`,`".join(keyArray)
        valueStringArray = []
        for data in self.dataArray:
            dataValues = data.values()
            tmpDataValues = []
            for value in dataValues:
                value = str(value)
                value = value.replace("\\","\\\\")
                value = value.replace("'","\\'")
                tmpDataValues.append(value)
            valueString = "('"+"','".join(tmpDataValues)+"')"
            valueStringArray.append(valueString)
        sql = "INSERT INTO `"+self.tableName+"` (`"+keyString+"`) VALUES " + ",".join(valueStringArray)
        if onDuplicateKey != "":
            sql = sql + " ON DUPLICATE KEY UPDATE " + onDuplicateKey
        self.lastSql = sql
        self.cursor.execute(sql)
        self.resetDefaultData()

    def find(self):
        sql = "SELECT "+self.fieldName+" FROM "+self.tableName+ self.whereStr + self.groupStr + self.orderStr + self.limitStr
        self.cursor.execute(sql)
        self.lastSql = sql
        results = self.cursor.fetchall()
        self.db.commit()
        self.resetDefaultData()
        return results

    def delete(self):
        sql = "DELETE FROM "+self.tableName+self.whereStr
        self.cursor.execute(sql)
        self.lastSql = sql
        self.db.commit()
        self.resetDefaultData()

    def save(self):
        setStrArray = []
        for key in self.dataDic:
            value = self.dataDic[key]
            value = str(value)
            value = value.replace("\\", "\\\\")
            value = value.replace("'", "\\'")
            setStr = "`"+str(key)+"` = '" + value + "'"
            setStrArray.append(setStr)
        if len(setStrArray) == 0:
            return
        setStrAll = ",".join(setStrArray)
        sql = "UPDATE "+ self.tableName + " SET " + setStrAll + self.whereStr
        self.lastSql = sql
        self.cursor.execute(sql)
        self.db.commit()

    def execute(self,sql):
        self.cursor.execute(sql)
        self.lastSql = sql
        results = self.cursor.fetchall()
        self.db.commit()
        self.resetDefaultData()
        return results

    def query(self,sql):
        self.cursor.execute(sql)
        self.lastSql = sql
        results = self.cursor.fetchall()
        self.db.commit()
        self.resetDefaultData()
        return results

    def close(self):
        self.db.close()

你可能感兴趣的:(python,数据库,数据库,sql,mysql,python)