将数据从Tweepy提交到sqlite3数据库,无论我做什么,db都保持为空

时间:2011-12-06 23:09:53

标签: python sqlite tweepy

代码:

import time
import tweepy
import sqlite3

class Listener(tweepy.StreamListener):

    conn = sqlite3.connect('/home/daniel/Desktop/activeSites/djeep/djeep.db')

    def on_status(self, status):
        try:
            c = self.conn.cursor()
            c.execute("""insert into feed_post values (%r,'%s','%s',%d)""") % (status.id, status.text, status.author.screen_name, status.created_at)
            self.conn.commit()
        except:
            pass


    def on_error(self, status_code):
        print 'An error has occured! Status code = %s' % status_code
        return True  # keep stream alive

    def on_timeout(self):
        print 'timeout...'

def main():
    auth = tweepy.OAuthHandler('C_KEY', 'C_SECRET') 
    auth.set_access_token('ACCESS_TOKEN', 'ACCESS_SECRET') 
    stream = tweepy.Stream(auth=auth, listener=Listener())     
    stream.filter(track=('baseball',)) 

if __name__=="__main__":
    try:
        main()
    except KeyboardInterrupt:
        print "See ya!"

我已经回去并且一次添加了一行数据库相关代码,试图找出它破坏了什么,似乎是添加了c.execute()行。我只是无法弄清楚我错过了什么!

2 个答案:

答案 0 :(得分:2)

数据库的路径应该是脚本的参数,而不是硬编码。每次实例化类时都应该将它提供给您的类,而不是在创建类时。然而,这不是问题的原因并不明显,而是问题的确切原因:

您的标题表明您无法将任何内容写入您的数据库,但问题正文表明,当您添加c.execute时,某些内容会“中断” - 这是正确的吗?当它“破裂”时有什么症状?

你的try \ yadda \ except \ pass默默地忽略所有可能的异常 - 不要这样做!删除try \ except \ pass只留下yadda,回答上述问题,然后让我们知道结果。

更新:您的c.execute()声明令人震惊。在不滚动的情况下使其清晰可辨,它等同于:

(
    c.execute("""insert into feed_post values (%r,'%s','%s',%d)""")
    % 
    (status.id, status.text, status.author.screen_name, status.created_at)
)

换句话说,你的右括号严重错位。结果在语法上是有效的,但肯定会在运行时导致异常。

更糟糕的是:你正在为自己的SQL注入攻击做好准备。使用参数而不是字符串格式:

sql = "insert into feed_post values (?,?,?,?)"
params = (status.id, status.text, status.author.screen_name, status.created_at)
c.execute(sql, params)

这种方法的一个好处是它应该运行得更快,因为引擎不需要为每一行写入一个通常不同的SQL语句来解析(或使其缓存被淹没)。

答案 1 :(得分:0)

尝试从课程中取出自我引用,或使用__init__函数初始化self.conn

def __init__(self):
    self.conn = sqlite3.connect('/home/daniel/Desktop/activeSites/djeep/djeep.db')

def on_status(self, status):
    try:
        c = self.conn.cursor()
        c.execute(SQL...)
        self.conn.commit()
    except:
        pass

我同意machin,但是在初始化对象时将连接和游标对象作为参数传递。