python脚本未保存到数据库中

2024-04-23 22:58:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习如何使用visualstudios和sqlite用python修改数据。我的任务是计算在一个文件中发现电子邮件的次数,并以一种方式组织它们,然后对每封电子邮件进行计数。然后我必须将它们作为一个名为Counts的表输入到SQLite中,该表有两行(org,count)。我编写了一个代码,运行程序并将其输出到visualstudios的输出屏幕上,但不输出到数据库。你知道吗

这是我的程序:

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

谢谢你的建议


Tags: thefromforexecuteifemailcountline
1条回答
网友
1楼 · 发布于 2024-04-23 22:58:39

您需要使用insert/update提交更改,而不需要在执行select语句后提交。你知道吗

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()

相关问题 更多 >