我对 python 很陌生,一直在研究我的树莓派来启动并运行一个脚本,以将数百万个传感器数据记录导入 sqlite。我想在交易中这样做,以提高流程效率。我正在尝试将事务分解为 10k 块,如下所示:Python CSV to SQLite
到目前为止我有
import csv, sqlite3, time
def chunks(data, rows=10000):
for i in range (0, len(data), rows):
yield data[i:i+rows]
if __name__ == "__main__":
t = time.time()
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS sensor;")
cur.execute("CREATE TABLE sensor(key INT, reading REAL);")
filename = 'dummy.csv'
reader = csv.reader(open(filename,"r"))
divdata = chunks(reader)
for chunk in divdata:
cur.execute('BEGIN TRANSACTION')
for col1, col2 in chunk:
cur.execute('INSERT INTO sensor (key, reading) VALUES (?, ?)', (col1, col2))
con.execute('COMMIT')
我在 python 3.2.3 中收到以下错误:
Traceback (most recent call last):
File "/home/pi/test1.py", line 20, in <module>
for chunk in divdata:
File "/home/pi/test1.py", line 4, in chunks
for i in range (0, len(data), rows):
TypeError: object of type '_csv.reader' has no len()
我显然在某处搞砸了块部分,因为没有块和事务,一切(基本插入)都可以正常工作。任何帮助表示赞赏。