SQLite清空表数据并将自增ID设为0

前端之家收集整理的这篇文章主要介绍了SQLite清空表数据并将自增ID设为0前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

转自:http://www.cnblogs.com/easonoutlook/archive/2012/11/20/2779329.html

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中定义自增列的方法如下:

CREATE TABLE TableName ( id INTEGER PRIMARY KEY AUTOINCREMENT,… );

sqlite数据库中包含自增列时,会自动建立一个名为 sqlite_sequence 的表。这个表包含两个列:name和seq。name记录自增列所在的表,seq记录当前序号(下一条记录的编号就是当前序号加1)。如果想把某个自增列的序号归零,只需要修改 sqlite_sequence表就可以了。

UPDATE sqlite_sequence SET seq = 0 WHERE name = ‘TableName’;

也可以直接把该记录删掉:

DELETE FROM sqlite_sequence WHERE name = ‘TableName’;

要想将所有表的自增列都归零,直接清空sqlite_sequence表就可以了:

DELETE FROM sqlite_sequence;

猜你在找的Sqlite相关文章