database - 将列表成对并使用 sqlite3 将它们写入 .db 文件

标签 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 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/

相关文章:

entity-framework - 在通用应用程序中使用 EF7 实现数据库优先

sqlite - 我们如何将 ORDER BY 和 LIMIT,OFFSET 子句应用于 cn1-data-access 中的 DAO.fetch(query)?

android - 无法将微调器选择的项目保存到数据库,它保存 android.sqlite.cursor@ 而不是字符串

MySQL 关系和连接

php - 将用户分配到我的 PHP 应用程序中的多个项目,最佳方法?

database - 使用 shell 脚本更新 PostgreSQL 表的每一行

Python 类型错误 : sort() takes no positional arguments

sql - RedoLog 在 Oracle 中是如何工作的?

arrays - python中有可变的二进制数组吗?

python - 从 python 中的数据框中删除多列