Using SQLite database in Android

The following steps are required to use SQLite database in Android:

  1. To create a database in an Android application, you can use the SQLiteOpenHelper class to create and manage the database. First, create a class that extends SQLiteOpenHelper and override the following methods:
  2. In the onCreate() method, we create database tables.
  3. Upgrade database tables in this method, onUpgrade().
  4. Open the database: Before using the database in the application, it is necessary to open the database first. You can open the database using the getWritableDatabase() method or the getReadableDatabase() method.
  5. Performing database operations: You can use the methods of the SQLiteDatabase class to perform database operations such as adding, deleting, modifying, and querying data. Some commonly used methods are as follows:
  6. Execute SQL statement using execSQL().
  7. insert(): to add data.
  8. delete(): remove data.
  9. update(): Data is being updated.
  10. query(): retrieve data.
  11. Close database: After the application finishes using the database, it should be closed to release resources. The close() method can be used to close the database.

Here is a simple example:

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 IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, name TEXT)";
        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String dropTableQuery = "DROP TABLE IF EXISTS mytable";
        db.execSQL(dropTableQuery);
        onCreate(db);
    }
}

// 使用数据库
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();

// 插入数据
ContentValues values = new ContentValues();
values.put("name", "John");
db.insert("mytable", null, values);

// 查询数据
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
while (cursor.moveToNext()) {
    int id = cursor.getInt(cursor.getColumnIndex("id"));
    String name = cursor.getString(cursor.getColumnIndex("name"));
    Log.d("Database", "id: " + id + ", name: " + name);
}

// 关闭数据库
db.close();

This is just a simple example, in actual use, more database operations may be needed. Additionally, attention should be paid to the design of data tables and data handling.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds