Android SQLite CRUD Guide

In Android, connecting to a database to perform CRUD operations typically involves using the SQLite database. Here are the general steps to implement CRUD operations.

  1. Create a database helper class that inherits from SQLiteOpenHelper to handle database creation, upgrades, and provide methods for database operations.
public class DBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "mydatabase.db";
    private static final int DATABASE_VERSION = 1;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableQuery = "CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)";
        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);
    }
}
  1. Instantiate DBHelper in the Activity or Fragment where database operations are needed to obtain a readable and writable database object.
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
  1. Perform CRUD operations on the database.
  1. Insert data.
ContentValues values = new ContentValues();
values.put("name", "John");
long result = db.insert("mytable", null, values);
  1. Data inquiry:
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
    do {
        String name = cursor.getString(cursor.getColumnIndex("name"));
        // 处理查询结果
    } while (cursor.moveToNext());
}
cursor.close();
  1. Update the data.
ContentValues values = new ContentValues();
values.put("name", "Mike");
int rowsAffected = db.update("mytable", values, "id=?", new String[] { "1" });
  1. Delete data:
int rowsAffected = db.delete("mytable", "id=?", new String[] { "1" });
  1. Close the database connection after finishing database operations.
db.close();

The above is a simple example of database operations, in actual applications, more complex operations may be performed based on specific needs. When performing database operations, it is important to pay attention to thread safety and exception handling to ensure the stability and security of data operations.

bannerAds