创建表并将数据流式传输到db文件后无法在sqlite中找到我的表

问题描述 投票:0回答:1

这是我第一次使用sqlite,我以前只在MySQL上工作过。我有一个程序,可以在其中直播实时Twitter推文,并将其存储在数据库中。该程序将创建一个数据库,然后开始运行tweepy以从twitter获取数据。我在尝试从数据库文件twitter.db中打印出数据以进行数据探索时遇到了麻烦。但是,我确实在控制台上看到了实时的tweets流,但似乎无法从db调用数据。

下面是我的数据库。

conn = sqlite3.connect('twitter.db')

c = conn.cursor()

def create_table():
    try:
        c.execute("CREATE TABLE IF NOT EXISTS sentiment(unix REAL, tweet TEXT, sentiment REAL)")  
        c.execute("CREATE INDEX fast_unix ON sentiment(unix)")
        c.execute("CREATE INDEX fast_tweet ON sentiment(tweet)")
        c.execute("CREATE INDEX fast_sentiment ON sentiment(sentiment)")
        conn.commit()
    except Exception as e:
        print(str(e))
create_table()

[我运行一次程序后,我将def create_table()函数添加了标签,以使数据流能够流传输而无需让程序运行另一个create_table()。下面是我如何将数据流传输到数据库。

    def on_data(self, data):
        try:
            data = json.loads(data)
            tweet = unidecode(data['text'])
            time_ms = data['timestamp_ms']

            analysis = TextBlob(tweet)

            sentiment = analysis.sentiment.polarity
            print(time_ms, tweet, sentiment)
            c.execute("INSERT INTO sentiment (unix, tweet, sentiment) VALUES (?, ?, ?)",
                  (time_ms, tweet, sentiment))
            conn.commit()

        except KeyError as e:
            print(str(e))
        return(True)

twitter API的流似乎运行良好,但是当我想打印我的行以进行数据探索并检查是否存储了数据时,出现此错误:OperationalError: no such table: sentiment。下面的代码产生上述错误:

import sqlite3

conn = sqlite3.connect('twitter.db')

c = conn.cursor()

c.execute("SELECT * FROM sentiment")

print(c.fetchall())

当我运行c.execute("SELECT * FROM sqlite_master")时...我在屏幕上打印了一个[]。我假设并知道有些错误。上面的代码有什么问题?

谢谢。

python sqlite tweepy
1个回答
0
投票

您是否从同一目录执行脚本?

如果不确定我建议同时使用两个脚本编写

import os
print("I am in following directory: ", os.getcwd())
conn = sqlite3.connect('twitter.db')

代替

conn = sqlite3.connect('twitter.db')

并检查两者是否真的在twitter.db的同一目录中>

如果这样做,则转到命令行将其切换到该目录并键入

sqlite3 twitter.db

然后输入]

.tables

并查看将列出哪些表。您甚至可以键入查询(如果该表存在)以进行更详细的检查

SELECT * FROM sentiment;
© www.soinside.com 2019 - 2024. All rights reserved.