将元组元素插入数据库
我有一个元组,里面有我想存储的元素。我尝试按照下面的方式插入,但出现了错误,我哪里做错了?records_to_be_inserted 是一个包含8个元素的元组。
with self.connection:
cur = self.connection.cursor()
cur.executemany("INSERT INTO rehberim(names, phone, mobile, email, \
photo, address, note, date) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", self.records_to_be_inserTed)
错误追踪(最近的调用在最前面): 文件 "/home/tayfun/workspace/personal_guide/modules/mainwindow.py",第57行,在 save_records photo, address, note, date) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", self.records_to_be_inserted) sqlite3.ProgrammingError: 提供的绑定数量不正确。当前语句需要8个,但提供了0个。
2 个回答
3
请注意,executemany
是用来一次性插入多行数据的,比如:
import sqlite3
""" the table structure is:
create table tab
a char(1),
b char(2),
c char(3)
)
"""
conn = sqlite3.connect('C:\\test.db')
stmt = "insert into tab (a, b, c) values (?, ?, ?)"
cur = conn.cursor()
## many rows
vals = [('1','2','3'), ('2','3','4'), ('3','4','5')]
cur.executemany(stmt, vals)
cur.close()
这样做会在数据库中生成三行数据。如果你在一个查询中有多个值,你需要对它进行格式化!
编辑:增加了使用字典进行格式化的方法
通过使用以下方法,你不需要考虑在 format
调用中值的顺序,因为字典中的键会把值映射到 {key_word}
这个占位符上。
values = {'a' : 'value_a',
'b' : 'value_b'}
stmt = "insert into tab (col_a, col_b) values ({a}, {b})".format(**values)
2
这个查询必须准备好所有要插入的数据。你在查询中调用了一个函数,我猜你是想通过这个函数来获取数据,但这样是行不通的。你需要把所有数据放在变量里,或者通过元组的索引来找到它们(比如:tuple_name[1],tuple_name[4],等等)。
举个例子:
myTuple = ['a','b','c','d','e','f','g']
cur.executemany("INSERT INTO rehberim(names, phone, mobile, email, \
photo, address, note, date) VALUES({0}, {1}, {2}, {3}, {4}, {5}, {6}" .format (myTuple[1], myTuple[2], myTuple[3], myTuple[4], myTuple[5], myTuple[6], myTuple[7])