【问题标题】:How to use cur.executemany() to store data from Twitter如何使用 cur.executemany() 存储来自 Twitter 的数据
【发布时间】:2019-08-31 21:50:14
【问题描述】:

我正在尝试从三个不同帐户的列表中下载推文,然后将所有信息存储在 SQL3 数据库中。

我已尝试使用下面的代码,但它似乎永远运行。我错过了什么吗?这是因为我使用了 .executemany() 而不是 .execute()?

step=0
a_list=["A","B","C"]
for s in a_list:
    cursor = tweepy.Cursor(api1.user_timeline, id = s, tweet_mode='extended').items(3189)

    for tweet in cursor: 
        tw_text.append(tweet.full_text)
        created_at.append(tweet.created_at)
        rtws.append(tweet.retweet_count)
        favs.append(tweet.favorite_count)
        for h in tweet.entities['hashtags']:
            hashlist.append(h['text'])
        for u in tweet.entities['urls']:
            linklist.append(u['expanded_url'])
        try:
            medialist.append(media['media_url'] for media in tweet.entities['media'])
        except:
            pass 
        step+=1
        print('step {} completed'.format(step))

#preparing all the data for .executemany()               
    g = [(s,tw,crea,rt,fv,ha,li,me) for s in ['GameOfThrones'] for tw in tw_text for crea in created_at for rt in rtws for fv in favs for ha in hashlist for li in linklist for me in medialist] 
    cur.executemany("INSERT INTO series_data VALUES (?,?,?,?,?,?,?,?)", (g))
    con.commit()
    print('db updated')

我希望程序在 SQL3 中写入表,但我从未收到“db updated”消息(即最后一行 print())

【问题讨论】:

    标签: sql python-3.x tweepy executemany


    【解决方案1】:

    cur.executemany() 采用元组列表。每个元组将包含与您要为其插入值的列数一样多的元素。

    例如,如果您有一个具有以下结构的表

    create table tbl_test(firstname varchar(20), lastname varchar(20));
    

    并且您想使用 executemany() 在其中插入 3 条记录,您的对象和调用应该如下所示

    list = [('Hans', 'Muster'), ('John', 'Doe'), ('Jane', 'Doe')]
    cur.executemany('insert into tbl_test values(?, ?)', list)
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2022-01-02
      • 1970-01-01
      • 2021-06-22
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      相关资源
      最近更新 更多