简体   繁体   English

SQLite executemany或联合选择可减少数据库写入

[英]Sqlite executemany or union select for reduced db writes

I'm trying to reduce the number of writes to a Sqlite database when it comes to inserting multiple rows into a table. 当要在表中插入多行时,我试图减少对Sqlite数据库的写入次数。

I've found two methods of doing this so far, using a union select statement or using the executemany command in sqlite3. 到目前为止,我已经找到了两种方法来执行此操作,即使用联合选择语句或在sqlite3中使用executemany命令。

Does executemany work via a single write? executemany是否可以通过一次写入工作?

For reference, please see the following statement I'm using (union select): 作为参考,请参阅我正在使用的以下语句(联合选择):

INSERT INTO table1
SELECT "hello" AS field1, 15 AS field2, 1262340000 AS timestamp 
UNION SELECT "byebye", 10, 1262340000 
UNION SELECT "hi", 20, 1262340000 
UNION SELECT "boo", 25, 1262340000 

UPDATE UPDATE

I'm aware building an SQL statement via string concatenation is really bad from a security point of view but in this case, the database owner is also the data provider so SQL injection issues can be ignored. 从安全的角度来看,我知道通过字符串连接构建SQL语句确实很糟糕,但是在这种情况下,数据库所有者也是数据提供者,因此可以忽略SQL注入问题。

This is for Python 2.7 这是针对Python 2.7

sqlite3 version 2.6.0 sqlite3版本2.6.0

SQLite flushes data from its page cache to disk when the transaction commits. 事务提交时,SQLite将数据从其页面缓存刷新到磁盘。 So you just need to put all the INSERTs into a single transaction: 因此,您只需要将所有INSERT放入一个事务中:

BEGIN;
INSERT INTO table1 VALUES('hello', 15, 1262340000);
INSERT INTO table1 VALUES('byebye', 10, 1262340000);
INSERT INTO table1 VALUES('hi', 20, 1262340000);
INSERT INTO table1 VALUES('boo', 25, 1262340000);
COMMIT;

Python automatically inserts transactions behind your back , so you can just use a bunch of execute() s, or executemany() : Python 自动在您的背后插入事务 ,因此您可以只使用一堆execute()executemany()

data = [('hello', 15, 1262340000),
        ('byebye', 10, 1262340000),
        ('hi', 20, 1262340000),
        ('boo', 25, 1262340000)]
con.executemany("INSERT INTO table1 VALUES(?, ?, ?);", data)
con.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM