SoFunction
Updated on 2025-03-02

Some key points of Android App using SQLite database

/DATA/data/package name/databases is the directory where the program stores data, and DATA is the path returned by the() method. After finding the database, you can select Export.
Use real machine to debug. If the data directory cannot be opened, it means that your phone does not have root, and it will be OK to switch to the emulator.

1. Get SQLiteDatabase object:

SQLiteDatabase db = openOrCreateDatabase(File file, , Factory factor);

The following methods are provided:

(sql)     //Execute any SQL statement(table, nullColumnHack, value)   //(increase)(table, whereClause, whereArgs)  //(delete)(table, values, whereClause, whereArgs) //(change)(table,columns,whereClause,whereArgs,groupBy,having,orderBy) //(check)(sql, selectionArgs)  //You can use SQL statements to query directly

3. Execute query and rawQuery operations to return a Cursor cursor object, which can traverse the contents of the entire query. Cursor provides the following methods to move the cursor:

( int offset)  //The cursor moves up or down the specified number of rows, positive number down, negative number up, negative number up()    //Move to the first row and return the boolean value()
()
(int postion)  //Move to the specified row and return the boolean value()  //Move to the previous line();       //Whether to point to the first item();       //Whether to point to the last one();  //Whether to point to the first item();   //Whether to point to the last one(int columnIndex); //Specify whether the column is empty (column cardinality is 0)();     //Is the cursor closed();    //Total number of data items();  //Return the number of rows pointed to by the current cursor(String columnName); //Return the column index value corresponding to a column name(int columnIndex);         //Return the value of the specified column in the current row

Below is an instance that creates a SQLiteDatabase object and only uses SQL statements to query

protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_main);
  //Each program has its own database and does not interfere with each other  //Create a database and open it. This method returns a SQLiteDadabase object (if there is no, create it, and if there is, open it directly)  //The name of this database is, so that it is named to facilitate third-party software to open after exporting to the computer. The second parameter is a constant. This example means that other private databases cannot be accessed  SQLiteDatabase db = openOrCreateDatabase("", MODE_PRIVATE, null);
  //Create a table usertb, and the primary key name is recommended to write it as _id, 1 primary key, 3 columns, plus _id, a total of 4 columns.   ("create table if not exists usertb(_id integer primary key autoincrement, name text not null, age integer not null, sex text not null)");
  //Add 3 pieces of data into this table usertb, 3 columns, and 3 corresponding values   ("insert into usertb(name, age, sex) values('Jack','18','male')");
   ("insert into usertb(name, age, sex) values('Hellen','19','female')");
   ("insert into usertb(name, age, sex) values('Mike','20','male')");

  //Query data. The first parameter is still a statement. The query method specifies how to find query conditions. The second parameter is the query conditions. All data is query by default.  //The return value here is Cursor, which is a class of the management set obtained after querying data. It can be understood as a list (cursor interface)  Cursor c = ("select * from usertb", null);
   if (c!= null){                    //If the data can be found     ();                //If the data has not been processed, this line can be omitted, the first line of the default cursor is the first line.     while(()){          //Only one data can be queried at a time to determine whether the next line can be queried (key point: after each cursor reaches one line, the following statement prints the data in that line in sequence, loops, and prints the next line of data)        ("info", " "+ (("_id")));       //The first field int type needs to be converted to String type before printing with Log (find the integer type data with field angle marked 0 in this data)       ("info", (("name")));      //The second field is text type       ("info", " "+(("age")));
       ("info", (("sex")));
       ("info", "~~~~~~~~");                          //Test how much data is printed in a loop     }
     ();                                  //After query, the cursor must be released   }
   ();    
}

4. Relevant parameters for adding, deleting, searching and modifying:

table: query data table name
columns: column name to be found
whereClause: Query the condition clause, allowing the use of placeholders "?"
whereArgs: Used to pass parameter values ​​for placeholders
groupBy: used to control grouping
having: used to filter packets
orderBy: used to sort records

ContentValues ​​is a wrapper for key/value. Using it, the data to be inserted or modified can be encapsulated in the form of key/value, and is used directly when using the corresponding addition and modification methods.
It has two methods of depositing and withdrawing:

put(String key,Xxx);
getAsXxx(String Key);

The following example uses built-in functions to operate the database to add, delete, modify and search:

  

 SQLiteDatabase db = openOrCreateDatabase("", MODE_PRIVATE, null);
  ("create table if not exists usertb(_id integer primary key autoincrement, name text not null, age integer not null, sex integer not null) ");

  //Before executing the addition and modification methods, first create a ContentValues ​​object in the insert method, then store data on this object, and insert values ​​into it after saving.  ContentValues values = new ContentValues(); 
  //increase  ("name", "Zhang San");
  ("age",18);
  ("sex","male");
  ("usertb", null, values);  //The return value of the insert method is a long, indicating the line number of the newly added record  ();    //Before inserting the next data, you need to clear the values ​​and then store the new data in the values  ("name", "Li Si");
  ("age",19);
  ("sex","male");
  ("usertb", null, values);  
  ();
  ("name", "Wang Wu");
  ("age",20);
  ("sex","male");
  ("usertb", null, values);  
  ();
  //Change (change the gender with id greater than female  ("sex", "female");
  ("usertb", values, "_id >?", new String[]{"2"});
  //Delete (Delete the person with three in his name)  ("uesrtb", "name like ?", new String [] {"%three%"});
  //Check (Query usertb table, all rows are bad, and the data with _id > 0 are checked, and the data found are sorted by name)  Cursor c = ("usertb", null, "_id > ?", new String[]{"0"}, null, null, "name");

  ();

  //Close the current database  ();
  //Delete the database (note that it is not the table name)  deleteDatabase("");

   
 : 
SQLiteOpenHelper is a helper class that manages our database by inheriting it and implementing the onCreate method and Upgrade method.

SQLiteDatabase db = ();
SQLiteDatabase db = ();

The following example is to create a new class to inherit SQLiteOpenHelper

public class DBOpenHelper extends SQLiteOpenHelper{    
  public DBOpenHelper(Context context, String name) {
    super(context, name, null, 1);
  }
  public DBOpenHelper(Context context, String name, CursorFactory factory,int version) {
    super(context, name, factory, version);
  }

  @Override//Called when creating a database for the first time. Generally, the operation of building a database and building a table can be used.  public void onCreate(SQLiteDatabase db) {
    ("create table if not exists stutb(_id integer primary key autoincrement,name text not null,sex text not null,age integer not null)");
    ("insert into stutb(name,sex,age)values('Zhang San','female',18)");
  }

  @Override//It will be automatically executed when the database version changes  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  }
}

Then you can create an object of this subclass in the main activity, and obtain the SQLiteDatabase object through the get method of this class

DBOpenHelper helper =new DBOpenHelper(, "");
SQLiteDatabase db = ();