【问题标题】:Import data from .csv to mysql into two tables using python使用python将数据从.csv导入mysql到两个表中
【发布时间】:2019-06-22 19:22:06
【问题描述】:

表中的数据通过 id 建立关系,例如stackoverflow 问题有它的标签、作者、发布时间。 试图编写一个代码,将标签和作者连接起来引用并将其插入 mysql。 我的报价存储在一个名为 Posts 的表中。 标签和作者都在一个表格中。

Example

【问题讨论】:

  • 那么你的实际问题是什么?
  • 在关系表中,我的帖子的 id=1 例如id=1 连接到 id=3(标签 id) id=1 连接到 id=10(作者 id) id=1 连接到 id=8(time_posted id)
  • @AbdukahhorKurbonov 数据存储在哪里?如果你有它在一个 .csv 然后导入到 mysql 就像:dev.mysql.com/doc/refman/8.0/en/load-data.html
  • 数据库中有 2 个表。第一个商店引用第二个标签和作者。每当它导入引用时,它也应该获取标签和作者。我的报价有 id=1 例如id=1 与 id=3 相关(标签 id) id=1 与 id=10 相关(作者 id) id=1 与 id=8 相关。
  • 据我了解:您想从单个 csv 输入创建 3 个表(帖子、标签、作者)。对于您想要的每个标签:将其与现有标签 id 匹配,或者如果它不存在,则添加新标签 id --> 在添加行时对每个作者执行相同操作 --> 然后将新帖子添加到带有插入标签或作者 ID 的帖子表

标签: python mysql csv


【解决方案1】:

您的 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`);

你的 python 代码看起来像这样

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))

这是未经测试的,但应该可以让您很好地了解要查找的内容。

This might be helpful for the SQL mechanic

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 2020-05-06
    • 2012-02-15
    • 2019-01-28
    • 1970-01-01
    • 2020-11-12
    • 2019-02-21
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多