Database 将列表转换为对,并使用sqlite3将它们写入.db文件
我需要一份信息列表,例如:Database 将列表转换为对,并使用sqlite3将它们写入.db文件,database,python-3.x,sqlite,Database,Python 3.x,Sqlite,我需要一份信息列表,例如: 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
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 |
您可以使用和executemany()
执行此操作:
literator=iter(my_list)
和zip(literator,literator)
使用space@inspectorG4dget你说得对,只是想展示一下这个想法……谢谢!我不明白代码的区别是什么。
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