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

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

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

python 复制代码
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博客

相关推荐
Ai 编码助手1 小时前
MySQL中distinct与group by之间的性能进行比较
数据库·mysql
陈燚_重生之又为程序员1 小时前
基于梧桐数据库的实时数据分析解决方案
数据库·数据挖掘·数据分析
caridle1 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
白云如幻1 小时前
MySQL排序查询
数据库·mysql
萧鼎1 小时前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
^velpro^1 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋31 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
荒川之神1 小时前
ORACLE _11G_R2_ASM 常用命令
数据库·oracle
IT培训中心-竺老师2 小时前
Oracle 23AI创建示例库
数据库·oracle
小白学大数据2 小时前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫