我需要获取信息列表,例如:
my_list = ['a','1','b','2','c','3','d','4']
我需要使用 sqlite3 将此信息成对写入 .db 文件中的两个单独的列中。
| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |
sqlite3 不允许我将列表作为参数传递,所以我很累:
connection = sqlite3.connect('mytest.db')
cursor = conn.cursor
cursor.execute('CREATE TABLE IF NOT EXISTS test(c1 TEXT, c2 TEXT)')
for i in my_list[0:len(my_list):2]:
cursor.execute(INSERT INTO test (c1) VALUES (?)',(i,))
connection.commit
for i in my_list[1:len(my_list):2]:
cursor.execute(INSERT INTO test (c2) VALUES (?)',(i,))
connection.commit
但是,这使得表格看起来像这样:
| a | null |
| b | null |
| c | null |
| d | null |
| null | 1 |
| null | 2 |
| null | 3 |
| null | 4 |
最佳答案
您可以使用 pairwise iteration 来做到这一点和 executemany()
:
def pairwise(iterable):
a = iter(iterable)
return zip(a, a)
my_list = ['a','1','b','2','c','3','d','4']
cursor.executemany("""
INSERT INTO
test (c1, c2)
VALUES
(?, ?)""", pairwise(my_list))
connection.commit() # note: you need to call the commit method
关于database - 将列表成对并使用 sqlite3 将它们写入 .db 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421509/