If the database in an application does not require external access, implement a Database Help class inherited from SQLiteOpenHelper to support database creation and version update, which cannot be implemented by SQLiteDataBase. however, SQLiteDataBase has some very important methods for database operations. It is used to create, delete, and query data tables.
Run the add, delete, and modify operations: db.exe cSQL (SQL); or db. insert (), db. delete (), db. update (), including creating and deleting data tables, can also be implemented through execSQLCopy codeThe Code is as follows: // create a table
Public boolean createTable (){
SQLiteDatabase db = dbHelper. getWritableDatabase ();
String SQL = "CREATE TABLE IF NOT EXISTS" + TABLE_NAME + "(ID INTEGER PRIMARY KEY, Name VARCHAR, Age INTEGER )";
Try {
Db.exe cSQL (SQL );
Return true;
} Catch (SQLException ex ){
Log. d (tag, "create table failure ");
Return false;
}
}
// Add data
Public boolean addData (){
String name = etname. getText (). toString ();
String age = etage. getText (). toString ();
SQLiteDatabase db = dbHelper. getWritableDatabase ();
String SQL = "insert into" + TABLE_NAME + "(name, age) values ('" + name + "', '" + age + "')";
Try {
Db.exe cSQL (SQL );
Return true;
} Catch (SQLException ex ){
Log. d (tag, "add data failure ");
Return false;
}
}
// Modify
Public boolean updateData (){
SQLiteDatabase db = dbHelper. getWritableDatabase ();
String SQL = "update" + TABLE_NAME + "set age = '2' where name like 'cb '";
Object [] bindArgs = {"cb "};
Try {
Db.exe cSQL (SQL, bindArgs );
Return true;
} Catch (SQLException ex ){
Log. d (tag, "update data failure ");
Return false;
}
}
Run the following data query method: db. rawQuery (SQL, selectionArgs); or db. query (table, columns, selection, selectionArgs, groupBy, having, orderBy );Copy codeThe Code is as follows: // query public void selectData (){
SQLiteDatabase db = dbHelper. getReadableDatabase ();
String [] columns = {"name "};
Cursor cursor = db. query (TABLE_NAME, columns, null );
String names = "";
While (cursor. moveToNext ()){
Int c = cursor. getColumnIndexOrThrow ("Name ");
String name = cursor. getString (c );
// <=>
// String name = cursor. getString (0); // only one column is queried.
If (names = ""){
Names = name;
} Else {
Names = names + "\ n" + name;
}
}
Tvname. setText (names );
// Another query method
// String SQL = "select name from" + TABLE_NAME;
// Curosr cursor = db. rawQuery (SQL, null );
}