gpt4 book ai didi

python - 将数据从 Tweepy 提交到 sqlite3 数据库,无论我做什么,数据库都是空的

转载 作者:行者123 更新时间:2023-11-28 17:51:57 24 4
gpt4 key购买 nike

代码:

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()线。我只是不知道我错过了什么!

最佳答案

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

您的标题表明您无法将任何内容写入您的数据库,但问题正文暗示当您在 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 注入(inject)攻击做好准备。使用参数而不是字符串格式:

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

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

关于python - 将数据从 Tweepy 提交到 sqlite3 数据库,无论我做什么,数据库都是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com