简体   繁体   English

使用 Python 将数据从 csv 导入数据库

[英]Importing data from csv to database using Python

I need to create a database using info from a csv file, format:我需要使用 csv 文件中的信息创建一个数据库,格式为:
name,house,birth example: name,house,birth示例:

Adelaide Murton,Slytherin,1982  
Adrian Pucey,Slytherin,1977

Then I need to export to the database after splitting the name in the following format: first | middle | last | house | birth然后我需要将名称拆分后导出到数据库中,格式如下: first | middle | last | house | birth first | middle | last | house | birth

Below is my code;以下是我的代码; it exports like 1st row only first name, 2nd row only middle name, 3d row only last name, 4th row only house, etc. and everything else appears NULL.它仅导出第一行的名字,第二行仅中间名,3d 行仅姓氏,第四行仅房屋等,其他所有内容均显示为 NULL。 I end up having 792 rows instead of 40 in my database.我的数据库中最终有 792 行而不是 40 行。 Output image Output 图像

import csv
import sys
import cs50

db = cs50.SQL("sqlite:///students.db")

if len(sys.argv) != 2:
        sys.exit("Usage: import.py file.csv")
    
with open(sys.argv[1],'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        x = row["name"].split()
        db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?,?,?,?,?)", x[0], x[1] if len(x)==3 else None, x[2] if len(x)==3 else x[1], row["house"], row["birth"])

Make sure the students table is empty before running import, otherwise all the rows from all the attempts, buggy or not, are in the database.在运行导入之前确保学生表为空,否则所有尝试的所有行,无论是否有错误,都在数据库中。 A bug that creates the described output would only insert approx 280 rows.创建描述的 output 的错误只会插入大约 280 行。 (7 db rows per 1 csv row) (每 1 个 csv 行 7 db 行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM