Python:如何将数组放入SQL数据库

时间:2013-10-28 14:33:26

标签: python arrays database sqlite

我希望你能帮助我解决这个问题: 我想在Python Sqlite3数据库中保存这样的数组。

test = {
    'Peter': {'A': 1, 'B': 1, 'C': 1, 'E': 1},
    'Jack': {'A': 1, 'B': 1, 'D': 1, 'E': 1}
}

对此有什么好处?

2 个答案:

答案 0 :(得分:2)

对SQLite使用standard Python DB API。您的数据可以映射到行,每个条目的键都是数据库表中的ID。

import sqlite3

d  = {
  'Peter': {'A': 1, 'B': 1, 'C': 1, 'E': 1},
  'Jack': {'A': 1, 'B': 1, 'D': 1, 'E': 1}
}

con = sqlite3.connect("/tmp/d.sqlite3")
cur = con.cursor()

cur.execute("create table t (id text, a integer, b integer, c integer, d integer, e integer)")
cur.executemany("insert into t values (?, ?, ?, ?, ?, ?)",
  [(k, v.get('A', None), v.get('B', None), v.get('C', None), v.get('D', None), v.get('E', None)) for k, v in d.items()])
con.commit()

cur.execute("select * from t")
cur.fetchall()

# [('Peter', 1, 1, 1, None, 1),
#  ('Jack', 1, 1, None, 1, 1)]

答案 1 :(得分:-2)

将dict序列化为JSON并将结果字符串存储在文本字段中。