Python SQLite fetchone()[0]

时间:2017-05-28 00:08:51

标签: python python-3.x sqlite

嗨,我正在学习python,我无法弄清楚这段代码。我理解这里的大部分内容,但无法弄清楚fetchone()[0]部分以及为什么当我将[0]更改为[1],[2]等时,我的表看起来并不那么好(每个电子邮件计数器)是1,因此如果文件中有多个相同的电子邮件,则每封电子邮件都是重复的。请帮我。

import sqlite3

con= sqlite3.connect('db1.sqlite')
cur=con.cursor()

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

cur.execute('CREATE TABLE TimesSend(email TEXT,times INTEGER)')

file=open('file.txt','r')

for row in file:
    if not row.startswith('From: '): continue
    parts= row.split()
    mail=parts[1]
    print(mail)
    cur.execute('SELECT timesFROM TimesSend WHERE email= ?',(mail,))
    try:
        times=cur.fetchone()[0]
        cur.execute('UPDATE TimesSend SET times=times+1 WHERE email=?',
(mail,))
    except:
        cur.execute('INSERT INTO TimesSend (email,puta) VALUES(?,1)',
(mail,) )
    con.commit()

1 个答案:

答案 0 :(得分:-1)

您的代码存在一些问题,请在下面尝试:

import sqlite3

con= sqlite3.connect('db1.sqlite')
cur=con.cursor()

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

cur.execute('CREATE TABLE TimesSend(email TEXT,times INTEGER)')

file=open('file.txt','r')

for row in file:
    if not row.startswith('From: '): continue
    parts= row.split()
    mail=parts[1]
    print(mail)
    cur.execute('SELECT times FROM TimesSend WHERE email= ?',(mail,))
    try:
        times=cur.fetchone()[0] # fetchone() will be a turple (1,), then you should use index 0 to select times 1
        print(times)
        cur.execute('UPDATE TimesSend SET times=? WHERE email=?',
(times+1,mail)) # if duplicate, times+1
    except:
        cur.execute('INSERT INTO TimesSend (email,times) VALUES(?,1)',
(mail,) )
    con.commit()
print(cur.execute('SELECT * FROM TimesSend').fetchall())
con.close()

打印输出将是:

testa@gmail.com
testa@gmail.com
1
testc@gmail.com
testd@gmail.com
testb@gmail.com
[(u'testa@gmail.com', 2), (u'testc@gmail.com', 1), (u'testd@gmail.com', 1), (u'testb@gmail.com', 1)]