将 python 字典转换为 sqlite

标签 python json sqlite dictionary

我基于读取 URL 文件,在 Python 2.7 中使用 6 个变量构建了一个 sqlite 数据库和表。

我使用 JSON 并创建了一个字典。该代码可以很好地读取所有内容并循环遍历键和值。

我需要将其插入到我的表中。那是我有点迷路的地方。我将提供代码,我认为我的漏洞很明显。

import json
import urllib2
#Read file and print a line
webFD=urllib2.urlopen("http://rasinsrv07.cstcis.cti.depaul.edu/CSC455/assignment4.txt")
tweet = webFD.readline()
tweet


#create dictionary
dictt=json.loads(tweet)

#print dictionary
dictt.keys()

#print values
dictt.values()

#loop through tweets
for (key, value) in dictt.items():
    print key, '->', value

#Created the DB
import sqlite3
conn = sqlite3.connect('twitter.db')
c = conn.cursor()

#Created the table for the tweets
c.execute("CREATE TABLE Tweet(created_at, id, text, source,    in_reply_to_user_ID,retweet_Count)")

这是我的断开连接。想要加载那些推文(字典中的 6 个键和值到推文表中:

for elt in tweet:
    currentRow = elt[:-1].split(", ")
    insert = """insert into Tweet values ('%s', '%s', '%s', '%s', '%s', '%s')""" %("created_at", "id", "text", 'source', 'in_reply_to_user_ID', 'retweet_Count')
    print insert

最佳答案

你在这里做的没有意义:

insert = """insert into Tweet values ('%s', '%s', '%s', '%s', '%s', '%s')""" %("created_at", "id", "text", 'source', 'in_reply_to_user_ID', 'retweet_Count')

使用 % 格式化文字字符串只是将每个 %s 替换为文字字符串。所以你会得到这个:

insert into Tweet values ('created_at', 'id', 'text', 'source', 'in_reply_to_user_ID', 'retweet_Count')

这显然是无稽之谈;您想要插入,而不是列名

可以——但不应该——通过将六个值放入 % 操作来解决这个问题,如下所示:

insert = """insert into Tweet values ('%s', '%s', '%s', '%s', '%s', '%s')""" % currentRow

但这仍然是个坏主意。如果其中一个值中包含引号会怎样? This .

想要做的是:

c.execute("insert into Tweet values (?, ?, ?, ?, ?, ?)", currentRow)

这让数据库处理值的格式化,确保它们被正确引用等。

关于将 python 字典转换为 sqlite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19822510/

相关文章:

Python CSV 到 SQLite

sqlite - React Native 和 sqlite 迁移

python - 如何在 Celery 任务执行期间强制记录器格式?

python - 如何向由条件语句形成的表添加新列?

javascript - 在 Node.js 中高级编写文件

java - 使用 Gson 反序列化 List<T> 对象?

android - 如何使介绍 Activity 仅出现一次?

python - 将 2-D numpy 数组附加到 3-D numpy 数组

python - Celery重启丢失定时任务

javascript - 我需要一个逻辑代码来动态创建下面的 json 结构