Python: Databases(SQLite)

The assignment is to write a code in Python that creates a SQLite3 database, reads a file, counts the number of org emails and prints them. I’ve included the code below. The program runs but does not create an SQLite file. The assignment states that it must create a .sqlite file but it does not create any. It just prints the result in the command line but does not create the needed SQL file. What to do, help

code:
import sqlite3

conn = sqlite3.connect(r’C:\Users\Gospel\Desktop\Py4e\demail.sqlite’)
cur = conn.cursor()

cur.execute(‘DROP TABLE IF EXISTS Counts’)

cur.execute(‘’’
CREATE TABLE Counts (org TEXT, count INTEGER)‘’')

fname = input('Enter file name: ‘)
if (len(fname) < 1): fname = r"C:\Users\Gospel\Desktop\Py4e\ex_15\mbox.txt"
fh = open(fname)
for line in fh:
if not line.startswith(‘From: ‘): continue
pieces = line.split()
orgemail = pieces[1]
emails = orgemail.find(’@’)
emailss = orgemail.find(’ ', emails)
email = orgemail[emails + 1 : emailss]

cur.execute('SELECT count FROM Counts WHERE org = ? ', (email,))
row = cur.fetchone()
if row is None:
    cur.execute('''INSERT INTO Counts (org, count)
            VALUES (?, 1)''', (email,))
else:
    cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?',
                (email,))

conn.commit()

sqlstr = ‘SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10’

for row in cur.execute(sqlstr):
print(str(row[0]), row[1])

cur.close()

Here is a link to the sqlite handbook. It should give you some guide to create sqlite databases and tables. How to populate and do queries.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.