Android: SQLite usage
Today we are talking about the use of SQLite:
Including:
1. Create a database;
2. Create a table;
3. insert data;
4. modify data;
5. delete data;
6. query data;
Directly attach the code (comments are included in the Code ):
MainActivity. java:
@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // create a database stu. db; SQLiteDatabase db = openOrCreateDatabase (stu. db, MODE_PRIVATE, null); // create a table; db.exe cSQL (create table if not exists stutb (_ id integer primary key autoincrement, name text not null, sex text not null, age integer not null); // create a ContentValues object, which is a Key-Value Pair storage, Key is a table field, Values is a value, and ContentValues values = new ContentValues (); // store key-value pairs similar to HashMap and use put to insert; values. put (name, Zhang San); values. put (sex, male); values. put (age, 15); // insert data into the table. The returned value type is the index value inserted by long. The first parameter is the table name, and the second parameter is set to null, the third is the ContentValues object; long rowId = db. insert (stutb, null, values); Log. I (info, rowId = + rowId); // clear the value in the ContentValues object to prepare for the next use; values. clear (); // insert multiple data entries below; values. put (name, Li Si); values. put (sex, male); values. put (age, 19); db. insert (stutb, null, values); values. clear (); values. put (name, Wang Wu); values. put (sex, male); values. put (age, 17); db. insert (stutb, null, values); values. clear (); values. put (name, Zhao Liu); values. put (sex, male); values. put (age, 29); db. insert (stutb, null, values); values. clear (); values. put (name, Lin 7); values. put (sex, female); values. put (age, 19); db. insert (stutb, null, values); values. clear (); // modify, change the gender of All IDS less than 3 to "female"; values. put (sex, female); db. update (stutb, values, _ id
?, New String [] {0}, null, null, _ id); if (cursor! = Null) {// obtain the index value of cursor, that is, all fields; String [] columnNames = cursor. getColumnNames (); while (cursor. moveToNext () {// retrieve the value of each field in the table through traversal for (String columnName: columnNames) {Log. I (info, cursor. getString (cursor. getColumnIndex (columnName);} // close the cursor; cursor. close () ;}// close the database; db. close ();}