2012-02-27 115 views
0

可能重复:
tweepy stream to sqlite database - invalid synatxtweepy流SQLite数据库 - 语法错误

我得到一个语法错误在我的代码,我无法弄清楚什么导致了它。这是控制台返回的错误,没有任何内容输入到sqlite文件。

Filtering the public timeline for "@lunchboxhq" 
RT @LunchboxHQ: @lunchboxhq test1 LunchboxHQ 2012-02-27 17:26:14 Echofon 
Encountered Exception: near "?": syntax error 
@LunchboxHQ test 1 LunchboxHQ 2012-02-27 17:26:36 Echofon 
Encountered Exception: near "?": syntax error 
@LunchboxHQ test 2 LunchboxHQ 2012-02-27 17:26:51 Echofon 
Encountered Exception: near "?": syntax error 

我sqlite的文件只有:

... tableTWEETSTWEETSCREATE TABLE TWEETS(txt text, author text, created int, source text) 

你们能帮我找出我做错了吗?谢谢。代码如下。

import sys 
import tweepy 
import webbrowser 
import sqlite3 as lite 

# Query terms 

Q = sys.argv[1:] 

sqlite3file='/var/www/twitter.lbox.com/html/stream5_log.sqlite' 

CONSUMER_KEY = '' 
CONSUMER_SECRET = '' 
ACCESS_TOKEN = '' 
ACCESS_TOKEN_SECRET = '' 

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) 

con = lite.connect(sqlite3file) 
cur = con.cursor() 
cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") 

class CustomStreamListener(tweepy.StreamListener): 

    def on_status(self, status): 

     try: 
      print "%s\t%s\t%s\t%s" % (status.text, 
             status.author.screen_name, 
             status.created_at, 
             status.source,) 

      cur.executemany("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, 
                  status.author.screen_name, 
                  status.created_at, 
                  status.source)) 

     except Exception, e: 
      print >> sys.stderr, 'Encountered Exception:', e 
      pass 

    def on_error(self, status_code): 
     print >> sys.stderr, 'Encountered error with status code:', status_code 
     return True # Don't kill the stream 

    def on_timeout(self): 
     print >> sys.stderr, 'Timeout...' 
     return True # Don't kill the stream 

streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60) 

print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),) 

streaming_api.filter(follow=None, track=Q) 

回答

2

executemany你有三个 “?” - 商标,但4个参数。它可能错过了一个额外的问号。你也可以只使用execute而不是executemany,因为你只做一个插入。就像这样:

cur.execute("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, 
               status.author.screen_name, 
               status.created_at, 
               status.source)) 

此外,根据this正确的SQL将是:

INSERT INTO TWEETS VALUES(?, ?, ?, ?) 
+0

仍然有同样的问题,即使添加了额外的后?它也没有写入正确的信息到sqlite文件。 – 2012-02-27 22:08:56

+0

@DavidNeudorfer我刚刚添加了关于使用'execute'的说明,这可能会有所帮助。 – Lycha 2012-02-27 22:12:06

+0

它没有工作。谢谢你的尝试。 – 2012-02-27 22:36:34