简体   繁体   English

让 SQLite 删除表中的所有记录

[英]Getting SQLite to delete all records in a table

I'm trying to delete all records in my MAIN_TABLE in my database located in my C:/ drive.. I'm using SQLite and I'm not on the Android platform.我正在尝试删除位于 C:/ 驱动器中的数据库中MAIN_TABLE中的所有记录。我正在使用SQLite ,但不在Android平台上。 I've only seen TURNCATE used in a couple of examples so I'm not 100% sure that is right..我只在几个例子中看到了TURNCATE ,所以我不能 100% 确定这是正确的..

CODE:代码:

package Exporter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DeleteAllRecords { 
//public void   runDeleteAllRecords()throws Exception, SQLException {
  public static void main(String[] argv) throws Exception {

String driverName = "org.sqlite.JDBC";
Class.forName(driverName);

String url = ("jdbc:sqlite:" + "C:/Test/DATABASE.db");
Connection connection = DriverManager.getConnection(url);
Statement stmt = connection.createStatement();

String sql = "TRUNCATE MAIN_TABLE";
stmt.executeUpdate(sql);
sql = "DELETE FROM MAIN_TABLE";
stmt.executeUpdate(sql);
}
}

ERRORS:错误:

Exception in thread "main" java.sql.SQLException: near "TRUNCATE": syntax error
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at Exporter.DeleteAllRecords.main(DeleteAllRecords.java:21)

SQLite does not have an actual TRUNCATE command. SQLite 没有实际的TRUNCATE命令。 Rather it has a truncate optimizer which will be used whenever you run DELETE without a WHERE clause.相反,它有一个 truncate 优化器,每当您运行DELETE而不使用WHERE子句时,都会使用该优化器。 So you should just use DELETE FROM without a WHERE clause to truncate your table:所以你应该只使用不带WHERE子句的DELETE FROM来截断你的表:

String sql = "DELETE FROM MAIN_TABLE";
stmt.executeUpdate(sql);

From the documentation :文档

The Truncate Optimization截断优化

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.当 DELETE 语句中省略 WHERE 并且被删除的表没有触发器时,SQLite 使用优化来擦除整个表内容,而不必单独访问表的每一行。 This "truncate" optimization makes the delete run much faster.这种“截断”优化使删除运行得更快。

"DELETE FROM MAIN_TABLE" maybe is not enough. “从 MAIN_TABLE 中删除”可能还不够。 Your data only marked as deleted but physically still in database file.您的数据仅标记为已删除但物理上仍在数据库文件中。

If you want zeros in place of your old data - you need second command "VACUUM".如果您想用零代替旧数据 - 您需要第二个命令“VACUUM”。

approximate code:大概代码:

String sql = "DELETE FROM MAIN_TABLE";
stmt.executeUpdate(sql);
sql = "VACUUM";
stmt.executeUpdate(sql);
db.execSQL("delete from "+ TABLENAME);

不要放星星

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

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