您可以通过以下步骤将 Excel 中的数据插入到 MySQL 数据库中的多张表中:
将 Excel 中的数据导出为 CSV 格式,以便后续导入 MySQL 数据库。在 Excel 中选择“另存为”选项,然后选择“CSV 格式”。
在 MySQL 数据库中创建对应的表,例如:
-- 机构表
CREATE TABLE IF NOT EXISTS orgnization (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
);
-- 网点表
CREATE TABLE IF NOT EXISTS outlet (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
);
-- 用户表
CREATE TABLE IF NOT EXISTS user (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
id_card VARCHAR(255) NOT NULL,
tel VARCHAR(255) NOT NULL,
card_time VARCHAR(255) NOT NULL,
flag VARCHAR(255) NOT NULL,
status VARCHAR(255) NOT NULL,
card_num VARCHAR(255) NOT NULL,
addr VARCHAR(255) NOT NULL,
area VARCHAR(255) NOT NULL,
org_id INT NOT NULL,
outlet_id INT NOT NULL,
FOREIGN KEY (org_id) REFERENCES orgnization(id),
FOREIGN KEY (outlet_id) REFERENCES outlet(id)
);
-- 所属辖区表
CREATE TABLE IF NOT EXISTS area (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
);
import mysql.connector
import csv
def import_data(file_path):
# 连接 MySQL 数据库
cnx = mysql.connector.connect(user='your_user', password='your_password',
host='your_host', database='your_database')
cursor = cnx.cursor()
# 打开 CSV 文件
with open(file_path, newline='', encoding='utf-8-sig') as csvfile:
reader = csv.DictReader(csvfile)
# 逐行读取 CSV 数据,并插入到对应的表中
for row in reader:
# 插入机构表
org_name = row['机构名称']
cursor.execute("INSERT INTO orgnization (name) VALUES (%s)", (org_name,))
org_id = cursor.lastrowid
# 插入网点表
outlet_name = row['网点']
cursor.execute("INSERT INTO outlet (name) VALUES (%s)", (outlet_name,))
outlet_id = cursor.lastrowid
# 插入用户表
user_name = row['姓名']
id_card = row['身份证']
tel = row['联系电话']
card_time = row['办卡时间']
flag = row['标识']
status = row['状态']
card_num = row['卡号']
addr = row['地区']
area = row['所属辖区']
cursor.execute("INSERT INTO user (name, id_card, tel, card_time, flag, status, card_num, addr, area, org_id, outlet_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
(user_name, id_card, tel, card_time, flag, status, card_num, addr, area, org_id, outlet_id))
# 插入所属辖区表
cursor.execute("INSERT INTO area (name) VALUES (%s)", (area,))
# 提交更改并关闭连接
cnx.commit()
cursor.close()
cnx.close()
import_data()
函数并将 CSV 文件的路径作为参数传递。例如:file_path = 'path/to/your/csv/file.csv'
import_data(file_path)
这样就可以将 Excel 中的数据插入到 MySQL 数据库中的多张表中了。
可以用Python吧