SQL标准中有TRUNCATE TABLE语句,用来清空表的所有内容。但SQLite不支持这个语句。在SQLite中直接使用“DELETE FROM TableName”就可以了。对于大多数DBMS来说,用DELETE不如用TRUNCATE 速度快,因为TRUNCATE 不用访问整个表,不用记录数据的变动。
SQLite虽然不支持TRUNCATE,但它对DELETE做了优化:“When the WHERE is omitted(略去) from a DELETE statement and the table being deleted has no triggers(触发器), SQLite uses an optimization(优化) to erase the entire table content without having to visit each row of the table individually. This “truncate” optimization makes the delete run much faster.”
通常在清空表的时候,还需要把自增列归零。在SQLite中定义自增列的方法如下:
1 |
CREATE TABLE TableName ( id INTEGER PRIMARY KEY AUTOINCREMENT, ... ); |
当SQLite数据库中包含自增列时,会自动建立一个名为 sqlite_sequence 的表。这个表包含两个列:name和seq。name记录自增列所在的表,seq记录当前序号(下一条记录的编号就是当前序号加1)。如果想把某个自增列的序号归零,只需要修改 sqlite_sequence表就可以了。
1 |
UPDATE sqlite_sequence SET seq = 0 WHERE name = ‘TableName‘; |
也可以直接把该记录删掉:
1 |
DELETE FROM sqlite_sequence WHERE name = ‘TableName‘; |
要想将所有表的自增列都归零,直接清空sqlite_sequence表就可以了:
1 |
DELETE FROM sqlite_sequence; |
SQLite清空表并将自增列归零[转],布布扣,bubuko.com