python3使用PyMySQL對mysql增刪查改工具類

python3使用PyMySQL對mysql增刪查改工具類

一個python3使用PyMySQL庫對mysql增刪查改的工具類,可用於web開發,python連接mysql當中,(複製就可用)

PyMySQL 是在 Python3.x 版本中用於連接 MySQL 服務器的一個庫,Python2中則使用mysqldb。

改良版:

#!/usr/bin/python3

# -*- coding: utf-8 -*-
import pymysql
import re

class MysqldbHelper(object): # 繼承object類所有方法

    '''
    構造方法:
    config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'passwd': 'root',
        'charset':'utf8',
        'cursorclass':pymysql.cursors.DictCursor
        }
    conn = pymysql.connect(**config)
    conn.autocommit(1)
    cursor = conn.cursor()
    '''

    def __init__(self , config):
        self.host = config['host']
        self.username = config['user']
        self.password = config['passwd']
        self.port = config['port']
        self.con = None
        self.cur = None

        try:
            self.con = pymysql.connect(**config)
            self.con.autocommit(1)
            # 所有的查詢,都在連接 con 的一個模塊 cursor 上面運行的
            self.cur = self.con.cursor()
        except:
            print("DataBase connect error,please check the db config.")

    # 關閉數據庫連接
    def close(self):
        if not  self.con:
            self.con.close()
        else:
            print("DataBase doesn't connect,close connectiong error;please check the db config.")

    # 創建數據庫
    def createDataBase(self,DB_NAME):
        # 創建數據庫
        self.cur.execute('CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci' % DB_NAME)
        self.con.select_db(DB_NAME)
        print('creatDatabase:' + DB_NAME)

    # 選擇數據庫
    def selectDataBase(self,DB_NAME):
        self.con.select_db(DB_NAME)

    # 獲取數據庫版本號
    def getVersion(self):
        self.cur.execute("SELECT VERSION()")
        return self.getOneData()

    # 獲取上個查詢的結果
    def getOneData(self):
        # 取得上個查詢的結果,是單個結果
        data = self.cur.fetchone()
        return data

    # 創建數據庫表
    def creatTable(self, tablename, attrdict, constraint):
        """創建數據庫表
            args:
                tablename  :表名字
                attrdict   :屬性鍵值對,{'book_name':'varchar(200) NOT NULL'...}
                constraint :主外鍵約束,PRIMARY KEY(`id`)
        """
        # 判斷表是否存在
        if self.isExistTable(tablename):
            print("%s is exit" % tablename)
            return
        sql = ''
        sql_mid = '`id` bigint(11) NOT NULL AUTO_INCREMENT,'
        for attr,value in attrdict.items():
            sql_mid = sql_mid + '`'+attr + '`'+' '+ value+','
        sql = sql + 'CREATE TABLE IF NOT EXISTS %s ('%tablename
        sql = sql + sql_mid
        sql = sql + constraint
        sql = sql + ') ENGINE=InnoDB DEFAULT CHARSET=utf8'
        print('creatTable:'+sql)
        self.executeCommit(sql)

    def executeSql(self,sql=''):
        """執行sql語句,針對讀操作返回結果集

            args:
                sql  :sql語句
        """
        try:
            self.cur.execute(sql)
            records = self.cur.fetchall()
            return records
        except pymysql.Error as e:
            error = 'MySQL execute failed! ERROR (%s): %s' %(e.args[0],e.args[1])
            print(error)

    def executeCommit(self,sql=''):
        """執行數據庫sql語句,針對更新,刪除,事務等操作失敗時回滾

        """
        try:
            self.cur.execute(sql)
            self.con.commit()
        except pymysql.Error as e:
            self.con.rollback()
            error = 'MySQL execute failed! ERROR (%s): %s' %(e.args[0],e.args[1])
            print("error:", error)
            return error

    def insert(self, tablename, params):
        """創建數據庫表

            args:
                tablename  :表名字
                key        :屬性鍵
                value      :屬性值
        """
        key = []
        value = []
        for tmpkey, tmpvalue in params.items():
            key.append(tmpkey)
            if isinstance(tmpvalue, str):
                value.append("\'" + tmpvalue + "\'")
            else:
                value.append(tmpvalue)
        attrs_sql = '('+','.join(key)+')'
        values_sql = ' values('+','.join(value)+')'
        sql = 'insert into %s'%tablename
        sql = sql + attrs_sql + values_sql
        print('_insert:'+sql)
        self.executeCommit(sql)

    def select(self, tablename, cond_dict='', order='', fields='*'):
        """查詢數據

            args:
                tablename  :表名字
                cond_dict  :查詢條件
                order      :排序條件

            example:
                print mydb.select(table)
                print mydb.select(table, fields=["name"])
                print mydb.select(table, fields=["name", "age"])
                print mydb.select(table, fields=["age", "name"])
        """
        consql = ' '
        if cond_dict!='':
            for k, v in cond_dict.items():
                consql = consql+'`'+k +'`'+ '=' + '"'+v + '"' + ' and'
        consql = consql + ' 1=1 '
        if fields == "*":
            sql = 'select * from %s where ' % tablename
        else:
            if isinstance(fields, list):
                fields = ",".join(fields)
                sql = 'select %s from %s where ' % (fields, tablename)
            else:
                print("fields input error, please input list fields.")
        sql = sql + consql + order
        print('select:' + sql)
        return self.executeSql(sql)

    def insertMany(self,table, attrs, values):
        """插入多條數據

            args:
                tablename  :表名字
                attrs        :屬性鍵
                values      :屬性值

            example:
                table='test_mysqldb'
                key = ["id" ,"name", "age"]
                value = [[101, "liuqiao", "25"], [102,"liuqiao1", "26"], [103 ,"liuqiao2", "27"], [104 ,"liuqiao3", "28"]]
                mydb.insertMany(table, key, value)
        """
        values_sql = ['%s' for v in attrs]
        attrs_sql = '('+','.join(attrs)+')'
        values_sql = ' values('+','.join(values_sql)+')'
        sql = 'insert into %s'% table
        sql = sql + attrs_sql + values_sql
        print('insertMany:'+sql)
        try:
            print(sql)
            for i in range(0,len(values),20000):
                    self.cur.executemany(sql,values[i:i+20000])
                    self.con.commit()
        except pymysql.Error as e:
            self.con.rollback()
            error = 'insertMany executemany failed! ERROR (%s): %s' %(e.args[0],e.args[1])
            print(error)

    def delete(self, tablename, cond_dict):
        """刪除數據

            args:
                tablename  :表名字
                cond_dict  :刪除條件字典

            example:
                params = {"name" : "caixinglong", "age" : "38"}
                mydb.delete(table, params)

        """
        consql = ' '
        if cond_dict!='':
            for k, v in cond_dict.items():
                if isinstance(v, str):
                    v = "\'" + v + "\'"
                consql = consql + tablename + "." + k + '=' + v + ' and '
        consql = consql + ' 1=1 '
        sql = "DELETE FROM %s where%s" % (tablename, consql)
        print(sql)
        return self.executeCommit(sql)

    def update(self, tablename, attrs_dict, cond_dict):
        """更新數據

            args:
                tablename  :表名字
                attrs_dict  :更新屬性鍵值對字典
                cond_dict  :更新條件字典

            example:
                params = {"name" : "caixinglong", "age" : "38"}
                cond_dict = {"name" : "liuqiao", "age" : "18"}
                mydb.update(table, params, cond_dict)

        """
        attrs_list = []
        consql = ' '
        for tmpkey, tmpvalue in attrs_dict.items():
            attrs_list.append("`" + tmpkey + "`" + "=" +"\'" + tmpvalue + "\'")
        attrs_sql = ",".join(attrs_list)
        print("attrs_sql:", attrs_sql)
        if cond_dict!='':
            for k, v in cond_dict.items():
                if isinstance(v, str):
                    v = "\'" + v + "\'"
                consql = consql + "`" + tablename +"`." + "`" + k + "`" + '=' + v + ' and '
        consql = consql + ' 1=1 '
        sql = "UPDATE %s SET %s where%s" % (tablename, attrs_sql, consql)
        print(sql)
        return self.executeCommit(sql)

    def dropTable(self, tablename):
        """刪除數據庫表

            args:
                tablename  :表名字
        """
        sql = "DROP TABLE  %s" % tablename
        self.executeCommit(sql)

    def deleteTable(self, tablename):
        """清空數據庫表

            args:
                tablename  :表名字
        """
        sql = "DELETE FROM %s" % tablename
        print("sql=",sql)
        self.executeCommit(sql)

    def isExistTable(self, tablename):
        """判斷數據表是否存在

            args:
                tablename  :表名字

            Return:
                存在返回True,不存在返回False
        """
        sql = "select * from %s" % tablename
        result = self.executeCommit(sql)
        if result is None:
            return True
        else:
            if re.search("doesn't exist", result):
                return False
            else:
                return True


if __name__ == "__main__":

    # 定義數據庫訪問參數
    config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'passwd': 'root',
        'charset': 'utf8',
        'cursorclass': pymysql.cursors.DictCursor
    }

    # 初始化打開數據庫連接
    mydb = MysqldbHelper(config)

    # 打印數據庫版本
    print(mydb.getVersion())

    # 創建數據庫
    DB_NAME = input('輸入要創建的數據庫名:')
    mydb.createDataBase(DB_NAME)

    # 選擇數據庫
    print("========= 選擇數據庫%s ===========" % DB_NAME)
    mydb.selectDataBase(DB_NAME)

    #創建表
    TABLE_NAME = input('輸入要創建的數據表名:')
    print("========= 選擇數據表%s ===========" % TABLE_NAME)
    '''例如
        CREATE TABLE `lisi` (
          `id` bigint(11) NOT NULL auto_increment,
          `name` varchar(30) NOT NULL,
          PRIMARY KEY  (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    '''
    print("========= 設置表的字段和屬性 ===========" )
    attrdict = {
        'name':'varchar(30) NOT NULL'
    }
    constraint = "PRIMARY KEY(`id`)"
    mydb.creatTable(TABLE_NAME,attrdict,constraint)
    print('首次創建以後,請手動刷新一下數據庫表頁面。')

    # 插入紀錄
    print("========= 單條數據插入 ===========")
    params = {}
    for i in range(5):
        params.update({"name":"testuser"+str(i)}) # 生成字典數據,循環插入
        print(params)
        mydb.insert(TABLE_NAME, params)
        print("")

    # 批量插入數據
    print("========= 多條數據同時插入 ===========")
    insert_values = []
    for i in range(5):
        # values.append((i,"testuser"+str(i)))
        insert_values.append([u"測試用戶"+str(i)]) # 插入中文數據
    print(insert_values)
    insert_attrs = ["name"]
    mydb.insertMany(TABLE_NAME,insert_attrs, insert_values)

    # 數據查詢
    print("========= 數據查詢 ===========")
    print(mydb.select(TABLE_NAME, fields=["id", "name"]))
    print(mydb.select(TABLE_NAME, cond_dict = {'name':'測試用戶1'},fields=["id", "name"]))
    print(mydb.select(TABLE_NAME, cond_dict = {'name':'測試用戶2'},fields=["id", "name"],order="order by id desc"))

    # 刪除數據
    print("========= 刪除數據 ===========")
    delete_params = {"name": "測試用戶2"}
    mydb.delete(TABLE_NAME, delete_params)

    # 更新數據
    print("========= 更新數據 ===========")
    update_params = {"name": "測試用戶99"}   # 需要更新爲什麼值
    update_cond_dict = {"name": "測試用戶3"}  # 更新執行的查詢條件
    mydb.update(TABLE_NAME, update_params, update_cond_dict)

    # 刪除表數據
    print("========= 刪除表數據 ===========")
    mydb.deleteTable(TABLE_NAME)

    # 刪除表
    print("========= 刪除表===================")
    mydb.dropTable(TABLE_NAME)

運行如圖:

在這裏插入圖片描述

數據庫:
在這裏插入圖片描述
完畢。


更多文章:
python_web 使用django框架完成個人博客管理系統(前端+後臺)

發佈了207 篇原創文章 · 獲贊 797 · 訪問量 95萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章