我基于读取 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/