python操作MySQL数据——连接与插入数据

一、前置准备

1、目录结构

python操作MySQL数据——连接与插入数据_第1张图片

2、数据准备

event_data.csv

id,name,`limit`,status,address,start_time
1,小米1,1000,1,某某会展中心101,2023/8/20 14:20
2,小米2,1001,1,某某会展中心102,2023/8/21 14:20

guest_data.csv

id,realname,phone,email,sign,event_id
1,张三,17712341234,[email protected],1,1
2,张无忌,17712341235,[email protected],1,1

3、数据库配置参数准备

db_config.ini

[mysqlconf]
host=127.0.0.1
port=3306
user=root
password=数据库密码
db_name=数据库名称

二、插入一个字典的数据

1、操作MySQL数据库mysql_db.py,代码如下:

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
            )
        except pymysql.err.OperationalError as e:
            print("Mysql Error %d : %s"%(e.args[0],e.args[1]))

    def clear(self,table_name):
        real_sql = "truncate  "+ table_name +";"
        # print(real_sql)
        with self.conn.cursor() as cursor:
            cursor.execute("SET FOREIGN_KEY_CHECKS=0;")
            cursor.execute(real_sql)
        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 + ") ;"
        print(real_sql)
        with self.conn.cursor() as cursor:
            cursor.execute(real_sql)
        self.conn.commit()

    def delete(self):
        pass

    def update(self,table_name,field_name,field_value,condition):
        pass

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


if __name__ == '__main__':
    table_name = "sign_event"
    db = DB()
    data = {'name': '小米14发布会2', '`limit`': 1000, 'status': 1, 'address': '某某会议中心',
            'start_time': '2023-08-20 00:25:42'}
    table_name2 = "sign_guest"
    data2 = {'realname': '张三2', 'phone': 12312341217, 'email': '[email protected]', 'sign': 0, 'event_id': 8}

    db.clear(table_name2)
    db.insert(table_name2,data2)


三、插入一个csv文件的数据

1、读取csv文件的数据readCsv.py,代码如下:

import csv
import codecs
import os
from itertools import islice
dirPath = os.path.dirname(os.path.dirname(__file__))
dirPath = dirPath.replace('\\','/')
event_Path = dirPath + '/data/event_data.csv'
guest_Path = dirPath + '/data/guest_data.csv'

class Csv_to_lst:
    def __init__(self,filePath):
        self.filePath = filePath

    def read_header(self):
        data_csv = csv.reader(codecs.open(self.filePath, 'r', 'gbk'))
        data = []
        for line in islice(data_csv,0,1):
            data.append(line)
        header = ','.join(data[0])
        return header

    def read_data(self):
        data_csv = csv.reader(codecs.open(self.filePath,'r','gbk'))
        data = []
        for line in islice(data_csv,1,None):
            data.append(line)
        result = []
        for item in data:
            # print(i) # ['1', '小米1', '1000', '1', '某某会展中心101', '2023/8/20 14:20']
            for i in range(0,int(len(item))):
                item[i] = "'" + str(item[i]) + "'"
            s = ','.join(item)
            result.append(s)
        return result
# ["'1','小米1','1000','1','某某会展中心101','2023/08/20 14:20'", "'2','小米2','1001','1','某某会展中心102','2023/08/21 14:20'"]

if __name__ == '__main__':
    obj = Csv_to_lst(guest_Path)
    data = obj.read_data()
    header = obj.read_header()
    print(header)
    print(data)

2、操作MySQL数据库mysql_db.py,代码如下:

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'  # 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
            )
        except pymysql.err.OperationalError as e:
            print("Mysql Error %d : %s"%(e.args[0],e.args[1]))

    # 清除数据表
    def clear(self,table_name):
        real_sql = "truncate  "+ table_name +";"
        # print(real_sql)
        with self.conn.cursor() as cursor:
            cursor.execute("SET FOREIGN_KEY_CHECKS=0;")
            cursor.execute(real_sql)
        self.conn.commit()

    # 插入数据
    def insert(self,table_name,file_path): # table_data是字典格式的数据
        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 + ") ;"
            print(real_sql)
            with self.conn.cursor() as cursor:
                cursor.execute(real_sql)
        self.conn.commit()


    def delete(self):
        pass

    def update(self):
        pass

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

if __name__ == '__main__':
    db = DB()
    db.clear(table_name)
    db.insert(table_name,event_Path)

3、运行结果

预期:

python操作MySQL数据——连接与插入数据_第2张图片

你可能感兴趣的:(Python,python,mysql)