【问题标题】:Updating Multiple Values with Dict in SQLite (Using Python)在 SQLite 中使用 Dict 更新多个值(使用 Python)
【发布时间】:2017-03-10 02:47:34
【问题描述】:

我正在尝试创建一个存储推文的 SQLite 数据库。每天我调用 API 并获得 10 万条左右的推文进行查询。

鉴于 Twitter API 可以追溯到 7 天,并且某些推文的某些值必然会发生变化(转发量、收藏夹等),我需要一种方法来更新数据库中已经存在的每条推文.

这就是我将新推文添加到数据库的方式(其中 'parsed' 是字典列表):

# query to add each tweet to the database
for tweet in parsed:
    c.execute("INSERT OR IGNORE INTO tweets VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
              [tweet['id'],
               tweet['url'],
               tweet['created_at'],
               tweet['hashtags'],
               tweet['favorite_count'],
               tweet['user_mentions'],
               tweet['text'],
               tweet['user_verified'],
               tweet['user_following_count'],
               tweet['retweet_count'],
               tweet['user_name'],
               tweet['user_id'],
               tweet['user_screen_name'],
               tweet['geo'],
               tweet['lang'],
               tweet['user_followers_count']]
             )

这是我迄今为止更新推文的查询:

update_tweet_query = '''UPDATE tweets
    SET url = ? ,
    created_at = ? ,
    hashtags = ? ,
    favorite_count = ? ,
    user_mentions = ? ,
    text = ? ,
    user_verified = ? ,
    user_following_count = ? ,
    retweet_count = ? ,
    user_name = ? ,
    user_id = ? ,
    user_screen_name = ? ,
    geo = ? ,
    lang = ? ,
    user_followers_count = ?
    WHERE id = ?'''

但我不知道如何从这里开始......我是否走在正确的轨道上?有没有更好的方法来做到这一点?

提前致谢!

【问题讨论】:

    标签: python sql twitter sqlite


    【解决方案1】:

    回答了我自己的问题...由于只有两个值会发生变化(收藏次数和转发次数),因此更新每个值是没有用的。因此,在解析数据时,我创建了另一个具有流体/动态值的 dict,并使用以下内容更新了数据库:

    update_query = 'UPDATE tweets SET favorite_count = ?, retweet_count = ? WHERE id = ?'
    
    for item in parsed[1]:
    
        # parsed[1][0] = {'favorite_count': 0, 'id': 838564895905964033, 'retweet_count': 229}
    
        curr_fav_count = item['favorite_count']
        curr_rt_count = item['retweet_count']
        curr_id = item['id']
    
        c.execute(update_query, (curr_fav_count, curr_rt_count, curr_id))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多