Home > Software design >  Why is my code not inserting any values into the db?
Why is my code not inserting any values into the db?

Time:05-01

The purpose of the code is to insert the data from the text file into a database with an empty table 'allmajors'.

The code runs without errors, but when I check the db, it is empty.

This are the contents of the text file I am using:

U1001,CyS,4.0

U9009,MATH,3.4,299,n

U6006,MATH,2.18

U7007,ART,3.0

U8008,CyS,3.5,322,y

import sqlite3

con = sqlite3.connect('students.sqlite')

f = open("students.txt", "r")
f_len = sum(1 for line in f)
print(f_len, "students are found in students.txt: ")
f.seek(0)
print(f.read())

cur = con.cursor()
#This is a test to see if manually inserting values would work, it didn't
cur.execute("INSERT INTO allmajors VALUES (1, 'Test', 1, 1, 'T')")

value = None
with open("students.txt") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        if len(row) < 4:
            cur.execute("INSERT INTO allmajors VALUES ((?), (?), (?), (?), (?))", [row[0], row[1], row[2], value, value])
        else:
            cur.execute("INSERT INTO allmajors VALUES ((?), (?), (?), (?), (?))", [row[0], row[1], row[2], row[3], row[4]])

CodePudding user response:

You need to do this:

cur.commit()

and finally:

con.close()
  • Related