0

File "import.py", line 58, in db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (name[0], NULL, name[1],house, birth)") File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 21, in decorator return f(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 385, in execute raise e RuntimeError: near "[0]": syntax error

import cs50
from sys import argv, exit
import csv



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

if len(argv) != 2:
    print("Usage: python [file name] [csv file]")
    exit(1)
            
# open the csv file
with open(argv[1], 'r') as csvfile:
            
            
    # read from the scv
    readcsv = csv.DictReader(csvfile)
    # loop through all the rows
    for row in readcsv:
        name = row['name'].split()
        house = row['house']
        birth = row['birth']
                
        # Insert into the database
        if (len(name) == 2):
            db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (name[0], NULL, name[1],house, birth)")
            print(name[0],"NULL",name[1], house, birth)
        else:
            db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (name[0], name[1], name[2],house, birth)")
            print(name[0],name[1],name[2], house, birth)
1

I just figured it out on the INSERT INTO am inserting variables so I have to format the string or in a better way use the "?" place holder so avoid SQL injections

db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", name[0], None, name[1],house, birth)
| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .