首页 > 解决方案 > 创建表并将数据流式传输到 db 文件后,无法在 sqlite 中找到我的表

问题描述

这是我第一次使用 sqlite,我之前只在 MySQL 上工作过。我有一个程序,我可以在其中流式传输实时 Twitter 推文并将它们存储在数据库中。该程序创建一个数据库,然后开始运行 tweepy 以从 twitter 获取数据。我在尝试从我的 db 文件中打印数据以进行数据探索时遇到问题,twitter.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")……我会[]在屏幕上打印出来。我假设并且知道有些事情是非常错误的。上面的代码有什么问题?

谢谢。

标签: pythonsqlitetweepy

解决方案


我认为gelonida是正确的,命令行sqlite3 是你的朋友。

我稍微修改了您的代码,当数据库位于同一位置时它可以正常工作:

import os
import sqlite3

os.remove('twitter.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 on_data():
    try:
        tweet = 'text'
        time_ms = 123.2
        sentiment = 1.234
        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)
on_data()

conn.close()

# Now check the result
conn = sqlite3.connect('twitter.db')
c = conn.cursor()
c.execute("SELECT * FROM sentiment")
print(c.fetchall())

运行它打印:

123.2 text 1.234
[(123.2, 'text', 1.234)]

推荐阅读