乐闻世界logo
搜索文章和话题

How to delete all records from table in sqlite with Android?

1个答案

1

In Android systems, to delete all records from an SQLite database table, you can execute a SQL DELETE statement. Here is a step-by-step guide with examples to help you understand how to perform this operation:

Step 1: Open or Create Database

First, ensure you have a working database instance, typically implemented using the SQLiteOpenHelper class. For example:

java
public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "example.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS records (_id INTEGER PRIMARY KEY, name TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS records"); onCreate(db); } }

Step 2: Delete All Records from the Table

Once the database is ready, you can execute a DELETE statement using the SQLiteDatabase instance to remove all records:

java
public void deleteAllRecords() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM records"); }

In this example, we directly use the execSQL method to execute a SQL command that clears the records table. This will delete all data from the table while preserving the table structure.

Step 3: Close the Database

After completing the operation, remember to close the database resources:

java
db.close();

Remarks:

  • Using DELETE FROM tableName; deletes all records from the table but does not reset the auto-increment field (if present). To reset the auto-increment field (e.g., _id), you can use DELETE followed by VACUUM, or delete and recreate the table.
  • In actual development, ensure proper exception handling and atomicity when operating on the database to prevent data errors or loss.
2024年8月14日 14:14 回复

你的答案