在 sqlite 中将字典作为行插入 table

insert dictionaries as rows in sqlite table

我有这样的词典:

{'id': 8, 'name': 'xyzzy', 'done': False}

table 已使用正确的列名(字典的键)创建。如何在相应的列中插入值?我想为每个字典创建一个新行。

请注意,对于 'done',定义的类型最初是 Integer,因为 sqlite 不提供 bool 类型。

cur = connection().cursor()
query = "insert .... tablename"

您可以使用 .format() 方法插入到查询字符串中,但这要简单得多。

dic = {'id': 8, 'name': 'xyzzy', 'done': False}

cur.execute("INSERT INTO tablename VALUES (:id,:name,:done)",{"id" : dic["id"],"name" : dic["name"],"done" : dic["done"]})

在Python中,数据库游标接受两个参数:

  1. 作为字符串的 SQL 语句:该语句可能包含占位符而不是某些值,以处理直到运行时才知道值的情况。
  2. 要插入到 SQL 语句中的 集合 。这些值在执行 SQL 语句时替换占位符。

占位符可以是位置的或命名的:

# Positional placeholders: the order of values should match the order of 
# placeholders in the statement.  Values should be contained with
# a tuple or list, even if there is only one.
cur.execute("""SELECT * FROM tbl WHERE name = ? AND age = ?""", ('Alice', 42))

# Named placeholders: values and placeholders are matched by name, order 
# is irrelevant.  Values must be contained within a mapping (dict) of
# placeholders to values.
cur.execute(
    """SELECT * FROM tbl WHERE name = :name AND age = :age""", 
    {'age': 42, 'name': 'Alice'}
)

您可以从字典到游标执行,只要 SQL 语句中的值占位符使用 :named 格式(即以冒号":").

conn = sqlite3.connect()
cur = conn.cursor()
stmt = """INSERT INTO mytable (id, name, done) VALUES (:id, :name, :done)"""
cur.execute(stmt, {'id': 8, 'name': 'xyzzy', 'done': False})
# Call commit() on the connection to "save" the data.
conn.commit()

此方法可确保在将值插入数据库之前正确引用值并防止 SQL 注入攻击。

另见 docs