请帮助我,我的import.py代码未能将所需数据输入数据库。我正在尝试将名称详细信息添加到字典中,然后在数据库中将其打印出来。我也想知道是否有更好的方法。这是下面的完整代码
from sys import argv, exit
from cs50 import SQL
from csv import reader, DictReader
# prompt to make sure user inputs csv file
if len(argv) != 2:
print("usage: python import.py (csv file)")
exit(0)
# open that file for sqlite
db = SQL("sqlite:///students.db")
# read the file using dictreader
file = open(argv[2], 'r')
csv_file = DictReader(file)
# iterate over csv file in dictread mode
for row in csv_file:
names = row['name'].split()
birth = row['birth']
house = row['house']
#create a dictionary to store names explicitly
if len(names) == 2:
names_defined = {
'first name': names[0],
'middle name': 'None',
'last name': names[1]
}
if len(names) == 3:
names_defined = {
'first name': names[0],
'middle name': names[1],
'last name': names[2]
}
for i in names_defined:
first = i['first name']
middle = i['middle name']
last = i['last name']
# store the above data in the students database
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
first,middle,last,house,birth)