我需要列出一些信息,例如:
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 |
答案 0 :(得分:1)
您可以使用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