python脚本没有保存到数据库中

时间:2018-05-25 00:38:26

标签: python python-3.x

我目前正在学习如何使用visual studio和sqlite使用python修改数据。我的任务是计算在文件中找到多少次电子邮件,然后按照每个电子邮件的计数方式对其进行整理。然后我必须将这些作为名为Counts的表输入到SQLite中,其中包含两行(org,count)。我编写了一个代码来运行程序并将其输出到visual studio输出屏幕而不是数据库。

这是我的计划:

import sqlite3

conn = sqlite3.connect('database3.db')
cur = conn.cursor()

cur.execute('DROP TABLE IF EXISTS Counts')

cur.execute('''CREATE TABLE Counts (email TEXT, count INTEGER)''')
#cur.execute("INSERT INTO Counts Values('mlucygray@gmail.com',1)")

# Save (commit) the changes
conn.commit()
fname = input('Enter file name: ')
if (len(fname) < 1): fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: '): continue
    pieces = line.split()
    email = pieces[1]
    cur.execute('SELECT count FROM Counts WHERE email = ? ', (email,))

    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (email, count) VALUES (?, 1)''', (email,))

    else:
        cur.execute('UPDATE Counts SET count = count + 1 WHERE email = ?',(email,))

    cur.execute('SELECT * FROM Counts')
# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'
conn.commit()
for row in cur.execute(sqlstr):
    print(str(row[0]), row[1])
    conn.commit()
cur.close()

click here for the link to the output of the above code

感谢您提出任何建议

1 个答案:

答案 0 :(得分:0)

您需要使用insert / update提交更改,并且在执行select语句后需要提交DONT。

for line in fh:
    if not line.lower().startswith('from: '): continue
    pieces = line.split()
    email = pieces[1]
    cur.execute('SELECT count FROM Counts WHERE email = ?', (email,))

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

    conn.commit()

sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'
for row in cur.execute(sqlstr):
    print(str(row[0]), row[1])
cur.close()