【问题标题】:Trouble inserting JSON data into sqlite3 database无法将 JSON 数据插入 sqlite3 数据库
【发布时间】:2021-10-25 05:54:16
【问题描述】:

我使用python创建了一个sqlite3数据库来存储数据,如下代码所示

import sqlite3
conn = sqlite3.connect('tweets_data.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS tweets')
cur.execute('''
    CREATE TABLE tweets (
        id INTEGER PRIMARY KEY, created_at TEXT, full_text TEXT, 
        favourite_count INTEGER, retweet_count INTEGER)
''')

使用此表,我想存储 JSON 文件中的数据(部分代码被截屏并附加为图像),我已加载如下所示

import json

with open('tweets.json') as f:
    data = json.load(f)

之后,我尝试使用 for 循环将数据插入表中,以提取所有唯一的推文 ID 及其以下信息。下面的代码是我尝试做的

for records in data:
    cur.execute('INSERT INTO tweets (id, created_at, full_text, favourite_count, retweet_count) VALUES (?, ?, ?, ?, ?)', 
                (records['id'], records['created_at'], records['full_text'], records['user']['favourites_count'], records['retweet_count']))
conn.commit()
print(cur.fetchall())
conn.close()

但是,当我进行打印 (cur.fetchall()) 时,输出只是一个空列表。表中没有插入任何内容。如果有人能提供帮助,谢谢!

json file page 1 json file page 2

【问题讨论】:

  • 如果可能,请在您的问题中添加 json 文件

标签: python json sqlite


【解决方案1】:

cur.fetchall() 返回最后一个查询的结果,INSERT 不产生任何结果。你首先需要一个SELECT-query:

cur.execute('SELECT * FROM tweets')
rows = cut.fetchall()

【讨论】:

  • 有效!!谢谢我是 SQL 新手,所以我对查询并不完全确定。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 2019-08-11
  • 1970-01-01
相关资源
最近更新 更多