首页 > 解决方案 > Python - 将 300 个变量插入 SQLite

问题描述

我每分钟从热传感器接收 300 个值。这 300 个值需要插入到 SQLite 数据库中,因为它们每分钟都会收到。

我在 SQLite 数据库中创建了 302 行,第一列是S_ID,第二列是timestamp. 在这里,S_ID每次添加一行时都会自动递增,timestampcolumn 的默认值是当前系统时间。我已经编程,每分钟接收 300 个热传感器值,将所有 300 个值放在一个名为的列表中data并插入data数据库。现在,我需要知道如何在executemany不写下所有 300 个列名及?以下的情况下编写语句。

data = [(300, 2, 4, ..., 5.5)] #these are 300 values that are inserted into a list when received from heat sensor
c.executemany('INSERT INTO heat_table (col3, col4, ..., col302) VALUES (?, ?, ..., ?)', data)

标签: pythondatabasesqliteinsertbulkinsert

解决方案


我会用列表推导创建这些名称,然后加入它们:

query = ('INSERT INTO heat_table (' +
         ', '.join('col%d' % i for i in range(3, len(data) + 3)) +
         ') VALUES (' +
         ', '.join('?' * len(data)) +
         ')')

推荐阅读