python - 使用python将数据从.csv导入mysql到两个表中
问题描述
表中的数据通过 id 建立关系,例如 stackoverflow 问题有其标签、作者、发布时间。试图编写一个代码,将标签和作者连接起来引用并将其插入 mysql。我的报价存储在一个名为 Posts 的表中。标签和作者在一个表中。
解决方案
您的 MYSQL Schema 应该使用以下内容创建:
CREATE TABLE Tags (
`id` smallint NOT NULL AUTO_INCREMENT ,
`name` longtext(250) NOT NULL UNIQUE,
PRIMARY KEY (`id`)
);
CREATE TABLE Authors (
`id` int AUTO_INCREMENT ,
`name` varchar(100) UNIQUE,
PRIMARY KEY (`id`)
);
CREATE TABLE Posts (
`id` tinyint unsigned AUTO_INCREMENT ,
`author_id` smallint NOT NULL ,
`tag_id` smallint NOT NULL ,
PRIMARY KEY (`id`)
);
ALTER TABLE `Posts` ADD FOREIGN KEY (author_id) REFERENCES Authors (`id`);
ALTER TABLE `Posts` ADD FOREIGN KEY (tag_id) REFERENCES Tags (`id`);
import csv
import mysql
# Setup database in some way to connect, depends on how you have your database setup
db
with open('posts.csv', 'rb') as f: #Open the file
c= csv.reader(f)
for row in c: #Assume there is no header row and read row by row
#Get the id of the tag
db.execute(""" INSERT INTO Tags (`name`) VALUES (%s) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)""", (row[0]))
tag_id = db.insert_id()
#Try to insert the author and if it exists get the id
db.execute(""" INSERT INTO Authors (`name`) VALUES (%s) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)""", (row[1]))
author_id = db.insert_id()
#Insert the row into the Posts table
db.execute(""" INSERT INTO Posts (`tag_id`, `author_id`) VALUES (%s, %s)""", (tag_id, author_id))
这是未经测试的,但应该让您很好地了解要查找的内容。
推荐阅读
- python - 如何使用python根据音符音高分割midi文件?
- flowtype - Flow 似乎在启动时无法解析文件
- android - 我无法在 android 中为自定义工具栏设置标题
- mysql - 在 mysql 的 Select 查询中传递动态参数
- python - 熊猫中一个向量与一个非常大的向量数据框的相似度排名
- javascript - 在 Angular 9 中使用 d3 地理地图
- javascript - Android Chrome 中的 Onbeforeunload 事件不会被触发
- python - 无法从函数正确返回布尔值
- sap-bw - SAP BW 数据加载后报告中的数据不完整
- python - 按字段名称从表中提取数据。Xpath,蟒蛇