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博客

相关推荐
tatasix10 分钟前
MySQL UPDATE语句执行链路解析
数据库·mysql
南城花随雪。22 分钟前
硬盘(HDD)与固态硬盘(SSD)详细解读
数据库
儿时可乖了24 分钟前
使用 Java 操作 SQLite 数据库
java·数据库·sqlite
懒是一种态度25 分钟前
Golang 调用 mongodb 的函数
数据库·mongodb·golang
天海华兮28 分钟前
mysql 去重 补全 取出重复 变量 函数 和存储过程
数据库·mysql
gma9991 小时前
Etcd 框架
数据库·etcd
爱吃青椒不爱吃西红柿‍️1 小时前
华为ASP与CSP是什么?
服务器·前端·数据库
Yz98762 小时前
hive的存储格式
大数据·数据库·数据仓库·hive·hadoop·数据库开发
武子康2 小时前
大数据-231 离线数仓 - DWS 层、ADS 层的创建 Hive 执行脚本
java·大数据·数据仓库·hive·hadoop·mysql
黑色叉腰丶大魔王2 小时前
《MySQL 数据库备份与恢复》
mysql