将Python列表输入SQLite

时间:2016-03-10 00:08:19

标签: python list sqlite

我正在尝试添加在解析每一行之后生成的列表。当我浏览每个代码时,我会得到不同的错误

(C:\Users\myname\Desktop\pythonCourse>dblesson2
Enter file name: mbox.txt
['uct.ac.za']
Traceback (most recent call last):
  File "C:\Users\myname\Desktop\pythonCourse\dblesson2.py", line 25, in      
    <module>
    #VALUES ( ?, 1 )''', ( email, ) )
sqlite3.OperationalError: near "#VALUES": syntax error) 

我知道这是因为我没有将正确的数据传递到数据库,但我无法自己解决这个问题。

import sqlite
import re

conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()

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

cur.execute('''
CREATE TABLE Counts (email TEXT, count INTEGER)''')

fname = raw_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
    line = line.rstrip()
    email = re.findall('@(\S+[a-zA-Z]+)', line)
    print email
    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, ))
# This statement commits outstanding changes to disk each 
# time through the loop - the program can be made faster 
# by moving the commit so it runs only after the loop completes
conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'

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

cur.close()`

2 个答案:

答案 0 :(得分:0)

您的程序中有许多小错误。让我试着列出它们:

  • re.findall返回一个列表,但您似乎将其视为单个字符串。请尝试email = email[0]仅考虑列表的第一个元素。
  • 您的第一个SELECT语句已(email)。将单个项放在括号内并不会使它成为元组。请改为(email,)[email]
  • if循环之后的for意味着在for循环的每次迭代中发生,因此必须缩进一次。
  • if的正文不能为空。取消注释该操作,或将其更改为pass
  • 最终for循环的正文需要缩进一个句点。
  • 作为Stack Overflow读者的礼貌,请复制粘贴整个独立程序,而不仅仅是片段。

解决问题之后,这是你的程序:

import sqlite3
import re

conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Counts''')

cur.execute('''
CREATE TABLE Counts (email TEXT, count INTEGER)''')

fname = raw_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
    line = line.rstrip()
    email = re.findall('@(\S+[a-zA-Z]+)', line)
    email = email[0]
    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, ))
# This statement commits outstanding changes to disk each 
# time through the loop - the program can be made faster 
# by moving the commit so it runs only after the loop completes
conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'

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

cur.close()

答案 1 :(得分:0)

import sqlite3
conn=sqlite3.connect('emaildb.sqlite')
cur=conn.cursor()

cur.execute('''DROP TABLE IF EXISTS counts''')
cur.execute('''CREATE TABLE counts (org TEXT, count INTEGER)''')

f_name=raw_input('Enter file name: ')
if len(f_name)<1   :   f_name='mbox.txt'
fn=open(f_name)
for line in fn:
   if not line.startswith('From: ') : continue 
   words = line.split()
   email=words[1]
   domain=email.split('@')
   organiz=domain[1]
   print organiz
   cur.execute('SELECT count FROM Counts WHERE org=?',(organiz, ))
   row=cur.fetchone()
   if row==None:
     cur.execute('''INSERT INTO counts (org, count) VALUES (?,1)''',
     (organiz, ))
   else:
     cur.execute('''UPDATE counts SET count=count+1 WHERE org=?''',(organiz, 
     ))
conn.commit()