问题
Possible Duplicate:
tweepy stream to sqlite database - invalid synatx
I'm getting a syntax error in my code and I can't figure out what's causing it. This is the error the console is returning and nothing is being inputed to the sqlite file.
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
my sqlite file only has:
... tableTWEETSTWEETSCREATE TABLE TWEETS(txt text, author text, created int, source text)
Can you guys help me figure out what I'm doing wrong? Thanks. The code is below.
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)
回答1:
On the executemany
you have three "?"-marks but 4 parameters. It is probably missing an additional questionmark. Also you should probably just use execute instead of executemany
since you only do one insert. Like this:
cur.execute("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text,
status.author.screen_name,
status.created_at,
status.source))
Also the correct SQL according to this would be:
INSERT INTO TWEETS VALUES(?, ?, ?, ?)
来源:https://stackoverflow.com/questions/9470308/tweepy-stream-to-sqlite-database-syntax-error