Json数据没有写入SQLite DB - Python

时间:2016-11-08 22:37:42

标签: python json sqlite

我的Json数据包含以下(但更大)

{
    "realms": [
        {

            "status": true,
            "battlegroup": "Shadowburn",
            "name": "Zuluhed",
            "locale": "en_US",
            "queue": false,
            "connected_realms": [
                "ursin",
                "andorhal",
                "scilla",
                "zuluhed"
            ],
            "timezone": "America/New_York",
            "type": "pvp",
            "slug": "zuluhed",
            "population": "medium"
        }
    ]
}

这是我的代码snipet应该将数据放入db文件 (json数据被加载到数据变量(data = json.loads(response)))

db=sqlite3.connect("temp.db")
c=db.cursor()
for record in data['realms']:
    c.execute('INSERT INTO realms (status, name, queue, timezone, type, population) VALUES (?,?,?,?,?,?)', (record['status'], record['name'],record['queue'], record['timezone'],record['type'], record['population']))

运行脚本运行没有错误,但检查表的内容没有任何内容

# sqlite3 temp.db
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> SELECT * FROM "realms";
sqlite> 
sqlite> .tables
realms
sqlite>

我是json和sqlite的新手所以我认为我做错了。 感谢

2 个答案:

答案 0 :(得分:2)

通过cursor对象对数据库执行的任何更新在提交之前都不会生效。在您的情况下,您与数据库的连接称为dbdb=sqlite3.connect("temp.db")),因此在db.commit()命令后的某处需要INSERT

答案 1 :(得分:0)

您可以将整个json转储到sqlite,然后从数据库中提取并做您想做的任何事情。

db=sqlite3.connect("temp.db")
cur = db.cursor()
sql_create_data_table= """CREATE TABLE IF NOT EXISTS myrealms (
                                id integer PRIMARY KEY AUTOINCREMENT,
                                data json NOT NULL
                            ); """
cur.execute(sql_create_data_table)

插入:

sql = '''INSERT INTO myrealms(data) VALUES(json('%s'))'''%json.dumps(response)
cur.execute(sql)
db.commit()

从数据库获取数据:

cur.execute("SELECT * FROM myrealms")
rows = cur.fetchall()
print(rows)
相关问题