当前位置: 首页 > article >正文

python操作MySQL——封装增删改查

上一篇:python操作MySQL数据——连接与插入数据-CSDN博客

下一篇:python操作mysql——批量添加csv数据-CSDN博客

import pymysql.cursors
from pymysql.err import OperationalError
from  data.readCsv import Csv_to_lst
import os
import configparser as cparser

base_dir = str(os.path.dirname(os.path.dirname(__file__)))
base_dir = base_dir.replace('\\','/')
file_path = base_dir + "/db_config.ini"
event_Path = base_dir + '/data/event_data.csv'
guest_Path = base_dir + '/data/guest_data.csv'

cf = cparser.ConfigParser()
cf.read(file_path)

host = cf.get("mysqlconf","host")
port = cf.get("mysqlconf","port")
user = cf.get("mysqlconf","user")
password = cf.get("mysqlconf","password")
db = cf.get("mysqlconf","db_name")

class DB:

    def __init__(self):
        try:
            self.conn = pymysql.connect(
                host=host,
                user=user,
                password=password,
                port=int(port),
                db=db,
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            self.cursor = self.conn.cursor()
        except pymysql.err.OperationalError as e:
            print("Mysql Error %d : %s"%(e.args[0],e.args[1]))

    def execute(self,sql):
        print(sql)
        self.cursor.execute(sql)
        rowcount = self.cursor.rowcount
        return rowcount

    def clear(self,table_name):
        real_sql1 = "SET FOREIGN_KEY_CHECKS=0;"
        real_sql2 = "TRUNCATE "+ table_name +";"
        self.execute(real_sql1)
        self.execute(real_sql2)
        self.conn.commit()

    def insert(self,table_name,table_data): # table_data是字典格式的数据
        for key in table_data:
            table_data[key] = "'"+str(table_data[key])+"'"
        key = ','.join(table_data.keys())
        value = ','.join(table_data.values())
        real_sql = "INSERT INTO " + table_name + "(" +key + ") VALUES (" + value + ") ;"
        self.execute(real_sql)
        self.conn.commit()

    def delete(self,table_name,data):
        global temp
        for k,v in data.items():
            i = int(len(v))
            if i!=0:
                if i==1:
                    temp = k +" = " + "'"+str(v[0])+"'"
                elif i>1:
                    s=str(v).replace('[','(').replace(']',')')
                    temp = k +" in " + s
        real_sql = "DELETE FROM " +table_name+ " WHERE "+temp
        self.execute(real_sql)
        self.conn.commit()

    def update(self,table_name,data,condition):
        # data = {'name': '小米14发布会2', 'address': '某某会议中心','start_time': '2023-08-20 00:25:42'}
        # update('my_table', data, condition="id in (1,2)")
        global real_sql
        set_lst = []
        for k, v in data.items():
            temp = k + "=" + "'" + str(v) + "'"
            set_lst.append(temp)
        set = ','.join(set_lst)
        if (table_name != '')and(set != ''):
            if condition != '':
                real_sql = "UPDATE " + table_name + " SET " + set + " WHERE " + condition+ " ; "
            elif condition == '':
                real_sql = "UPDATE " + table_name + " SET " + set + " ; "
            self.execute(real_sql)
            self.conn.commit()

    def select(self,table_name,field,condition,top):
        global data
        real_sql = "SELECT " + field + " FROM " + table_name + " WHERE " + condition +  ";"
        self.execute(real_sql)
        if top == 1:
            data = self.cursor.fetchone()
        elif 1<top:
            data = self.cursor.fetchmany(top)
        elif top<1:
            data = self.cursor.fetchall()
        return data

    def close(self):
        self.conn.close()

    # 批量插入csv文件的数据
    def init_data(self,table_name,file_path):
        self.clear(table_name)
        obj = Csv_to_lst(file_path)
        data = obj.read_data()
        key = obj.read_header()
        for value in data:
            real_sql = "INSERT INTO " + table_name + "(" + key + ") VALUES (" + value + ") ;"
            self.execute(real_sql)
        self.conn.commit()

if __name__ == '__main__':
    table_name = "sign_event"
    table_name2 = "sign_guest"
    db = DB()
    # 导入csv表格的数据
    # db.clear(table_name)
    # db.clear(table_name2)
    # db.init_data(table_name,event_Path)
    # db.init_data(table_name2,guest_Path)

    # 插入数据
    # data = {'name': '小米14发布会2', '`limit`': 1000, 'status': 1, 'address': '某某会议中心',
    #         'start_time': '2023-08-20 00:25:42'}
    # data2 = {'realname': '张三2', 'phone': 12312341217, 'email': 'XX1@mail.com', 'sign': 0, 'event_id': 8}
    # db.insert(table_name,data)
    # db.insert(table_name2,data2)

    # 更新数据
    # set_event = {'name': '小米14发布会', 'address': '某某会议中心','start_time': '2023-08-22 00:25:42'}
    # db.update(table_name,set_event,condition="id in (1,2)")
    # set_guest = {'sign':1}
    # db.update(table_name2,set_guest,condition='event_id=1 and sign=0')

    # 删除数据
    # del_data={'id':[7,8]}
    # db.delete(table_name,del_data)
    # db.delete(table_name2,del_data)

    # 查询数据
    select_data = db.select(table_name2,'*',"sign='0'",3)
    print(select_data)

上一篇:python操作MySQL数据——连接与插入数据-CSDN博客

下一篇:python操作mysql——批量添加csv数据-CSDN博客


http://www.kler.cn/a/161987.html

相关文章:

  • STM32问题集
  • 成都睿明智科技有限公司解锁抖音电商新玩法
  • 基于微信小程序的农场管理系统的设计与实现,LW+源码+讲解
  • HarmonyOS的@State装饰器的底层实现
  • 【MySQL 保姆级教学】事务的隔离级别(详细)--下(13)
  • 建筑施工特种作业人员安全生产知识试题
  • WT2605C蓝牙音频语音芯片:具备大功率IO驱动能力,引领音频技术新纪元
  • 循环中存在异步的情况如何让其正常执行?
  • 突破浅水、低流速,中海达iFlow系列智能型ADCP创新“低”!
  • Module build failed : Error : Vue packages version mismatch:
  • C#中的Attributes特性创建和结合反射应用举例
  • 苏宁商家电话采集软件使用教程
  • 生活、工作常用API免费接口
  • python socket编程6 - 使用PyQt6 开发UI界面实现TCP server和TCP client单机通讯的例子
  • 神经网络常用归一化和正则化方法解析(二)
  • axios调接口传参特殊字符丢失的问题(encodeURI 和 encodeURIComponent)
  • 【学习笔记】python仅拷贝list的值,引出浅拷贝与深拷贝
  • 在Python中,*f和**f是用于解包参数的语法
  • linux安装mysql5.7(一遍过)
  • 案例060:基于微信小程序考试系统
  • Java 简易版 UDP 多人聊天室
  • ThinkPHP插件开发实例
  • vue 使用 h函数
  • 区块链optimism主网节点搭建
  • 2024年值得关注的8个未来数据库
  • 什么是https 加密协议?