![](/img/trans.png)
[英]Import Specific Column Data into Different MYSQL Tables from CSV using Python
[英]Import data from .csv to mysql into two tables using python
表中的数据通过 id 有关系,例如 stackoverflow 问题有其标签、作者、发布时间。 试图编写一个将标记和作者连接起来以引用并将其插入到 mysql 的代码。 我的报价存储在一个名为 Posts 的表中。 标签和作者在一个表格中。
你的 MYSQL 架构应该是这样创建的:
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))
这是未经测试的,但应该让您对要查找的内容有一个很好的了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.