将Python字典转换为SQLite数据库

3

我在Python 2.7中使用读取URL文件的方式,构建了一个基于6个变量的sqlite db和table。

我使用了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

我们不知道源数据的样子。而且这不是在Python中执行查询的方式。 - Ignacio Vazquez-Abrams
这似乎是一道作业问题... - adam
这是一个作业问题,完全公开透明。我们得到了许可(即获准)在遇到困难时使用Stackoverflow。 - mpg
@adam 在这里问作业问题是可以的。并没有特别的“限制”;质量等方面的标准仍然适用,而且这个问题并不差。 - Andrew Barber
2个回答

3
你在这里做的事情毫无意义:
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

但是这仍然是个不好的想法。如果其中一个值中包含引号会发生什么?请参考这里

希望做的是这样的:

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

这样做可以让数据库处理格式化值,确保它们被正确地引用等。

1
我注意到两个错误:
  • 你只检索了一条推文
  • 字典的某些键拼写错误(Python区分大小写)
尝试这个。它不是最好的解决方案(它会不断打开/关闭数据库),但它非常类似于您发布的那个。
import json
import urllib2
#Read file and print a line
webFD = urllib2.urlopen("http://rasinsrv07.cstcis.cti.depaul.edu/CSC455/assignment4.txt")
tweets = webFD.readlines()

for tweet in tweets:
    print tweet


    #create dictionary
    try:
        dictt = json.loads(tweet)
    except ValueError:
        continue

    #print dictionary
    print dictt.keys()

    #print values
    print 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 IF NOT EXISTS Tweet(created_at, id, text, source,    in_reply_to_user_ID,retweet_Count)")

    #*** Here is a possible solution ***
    c.execute('INSERT INTO Tweet VALUES (?, ?, ?, ?, ?, ?)',
          (dictt['created_at'], dictt["id"], dictt["text"], dictt['source'], dictt['in_reply_to_user_id'],
           dictt['retweet_count']))
    conn.commit()
    conn.close()

太好了。经过几天的努力,终于成功读取了一条推文。那么,如果我想自动化这个过程、循环读取并加载文件中的所有推文,应该怎么改呢? - mpg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接