What is SQLiteDatabase?
An instance of SQLiteDatabase represents a database of SQLite. Through some methods of the instance of SQLiteDatabase, we can execute SQL statements to add, delete, search and modify the database. It should be noted that the database is private to an application, and the name of the database is also unique within an application.
What is SQLiteOpenHelper?
According to the name, we can see that this class is an auxiliary class. This class mainly generates a database and manages the version of the database. When the method getWritableDatabase() or getReadableDatabase() of this class is called in the program, if there is no data at that time, the Android system will automatically generate a database. SQLiteOpenHelper is an abstract class, we usually need to inherit it and implement the three functions inside.
What is the ContentValues class?
The ContentValues class is similar to Hashmap/Hashtable. It is also responsible for storing some name-value pairs, but the name of the name-value pairs it stores is a String type, and the values are all basic types.
What is Cursor?
Cursor is a very useful interface in Android. Through Cursor, we can perform random read and write access to the result set queried from the database.
SQLiteDatabase class introduction:
The SQLiteDatabase class provides us with many methods; for add, update and delete, we can use
1 db.executeSQL(String sql);
2 db.executeSQL(String sql, Object[] bindArgs);//A placeholder is used in the sql statement, and then the second parameter is the actual parameter set
In addition to the unified form, they also have their own methods of operation:
1 db.insert(String table, String nullColumnHack, ContentValues values);
2 db.update(String table, Contentvalues values, String whereClause, String whereArgs);
3 db.delete(String table, String whereClause, String whereArgs);
The first parameter of the above three methods is the name of the table to be operated; the second parameter in insert indicates that if each column of the inserted data is empty, you need to specify the name of a column in this row, the system will use this The column is set to NULL, so that no error occurs; the third parameter in insert is a variable of type ContentValues, which is a Map composed of key-value pairs. The key represents the column name, and the value represents the value to be inserted in the column; the second parameter of update The parameters are also similar, except that it updates the key of the field to the latest value. The third parameter whereClause represents a WHERE expression, such as "age > ? and age < ?", etc. The last whereArgs parameter is a placeholder The actual parameter value; the same is true for the parameters of the delete method
The demo is given below:
open database //db = SQLiteDatabase.openOrCreateDatabase("/data/data/com.hh.firstdemo/userTb.db", null); db = this.openOrCreateDatabase("userTb.db", MODE_PRIVATE, null); str_sql = "select count(*) as c from sqlite_master where type='table' and name='" + TABLE_NAME + "';"; cursor = db.rawQuery(str_sql, null); if (cursor.moveToNext()) { int count = cursor.getInt(0); if (count < 1) { str_sql = "create table " + TABLE_NAME + " (id integer primary key,name text,age integer,gender text);"; Log.d("sql", str_sql); db.execSQL(str_sql); } } cursor.close();
data addition String strName = txtName.getText().toString(); Integer intAge = Integer.parseInt(txtAge.getText().toString()); String strGender = txtGender.getText().toString();
1. Use the insert method ContentValues cv = new ContentValues();//Instantiate a ContentValues to load the data to be inserted cv.put("name", strName);//Add fields and content cv.put("age", intAge); cv.put("gender", strGender); db.insert(TABLE_NAME, null, cv);//Execute insert operation
2. Use execSQL method to achieve str_sql = "insert into " + TABLE_NAME + " (name,age,gender) values ('" + strName + "'," + intAge + ",'" + strGender + "');"; db.execSQL(str_sql);//Execute SQL statement
Data deletion String id = spinner.getSelectedItem().toString();
1. Use the delete method String whereClause = "id=?";//Deletion condition String[] whereArgs = {id};//Deleted conditional parameters db.delete(TABLE_NAME, whereClause, whereArgs);//Execute delete
2. Use execSQL method to achieve str_sql = "delete from " + TABLE_NAME + " where id = " + id + ";";//SQL statement for delete operation db.execSQL(str_sql);//Execute delete operation for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(id)) { list.remove(i); adapter.notifyDataSetChanged(); } }
data modification String id = spinner.getSelectedItem().toString(); String strName = txtName.getText().toString(); Integer intAge = Integer.parseInt(txtAge.getText().toString()); String strGender = txtGender.getText().toString();
1. Use the update method ContentValues cv = new ContentValues();//Instantiate ContentValues cv.put("name", strName);//Add the fields and content to be changed cv.put("age", intAge); cv.put("gender", strGender); String whereChsuse = "id=?";//Modify the condition String[] whereArgs = {id};//Modify the parameters of the condition db.update(TABLE_NAME, cv, whereChsuse, whereArgs);//Execute modification
2. Use execSQL method to achieve str_sql = "update " + TABLE_NAME + " set name='" + strName + "'," +"age=" + intAge + ",gender='" + strGender + "' " +"where id=" + id + ";";//Modified SQL statement db.execSQL(str_sql);//Execute modification
data query
Let's talk about query operations. The query operation is more complicated than the above operations, because we often face various query conditions, so the system also takes this complexity into consideration and provides us with a richer query form:
db.rawQuery(String sql, String[] selectionArgs);
db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);
db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
The above are all commonly used query methods. The first one is the simplest. All SQL statements are organized into a string, and placeholders are used to replace actual parameters. SelectionArgs is the actual parameter set of placeholders;
Description of each parameter:
table: table name
columns: Indicates the set of all names of the columns to be queried
selection: indicates the conditional statement after WHERE, you can use placeholders
selectionArgs: Array of parameters for the conditional statement
groupBy: Specify the column name of the grouping
having: specify grouping conditions, used with groupBy
orderBy: y specifies the column name for sorting
limit: Specify paging parameters
distinct: Specify "true" or "false" to indicate whether to filter duplicate values
Cursor: return value, equivalent to the result set ResultSet
Finally, they also return a Cursor object, which represents the cursor of the dataset, somewhat similar to the ResultSet in JavaSE. The following are common methods of Cursor objects:
c.move(int offset); //Use the current position as a reference, move to the specified line
c.moveToFirst(); //move to the first line
c.moveToLast(); //move to the last line
c.moveToPosition(int position); //Move to the specified row
c.moveToPrevious(); //move to the previous line
c.moveToNext(); //move to the next line
c.isFirst(); //Whether it points to the first article
c.isLast(); //Whether it points to the last one
c.isBeforeFirst(); //Does it point to before the first
c.isAfterLast(); //Whether it points to after the last one
c.isNull(int columnIndex); //Specify whether the column is empty (the column cardinality is 0)
c.isClosed(); //Whether the cursor is closed
c.getCount(); //Total number of data items
c.getPosition(); //Returns the number of rows pointed to by the current cursor
c.getColumnIndex(String columnName);//Return the column index value corresponding to a column name
c.getString(int columnIndex); //Returns the value of the specified column in the current row
implementation code
String[] params = {12345,123456};
Cursor cursor = db.query("user",columns,"ID=?",params,null,null,null);//Query and get the cursor
if(cursor.moveToFirst()){//Determine whether the cursor is empty
for(int i=0;i<cursor.getCount();i++){
cursor.move(i);//Move to the specified record
String username = cursor.getString(cursor.getColumnIndex("username");
String password = cursor.getString(cursor.getColumnIndex("password"));
}
}
Query with parameters implemented by rawQuery
Cursor result=db.rawQuery("SELECT ID, name, inventory FROM mytable");
//Cursor c = db.rawQuery("s name, inventory FROM mytable where ID=?",new Stirng[]{"123456"});
result.moveToFirst();
while (!result.isAfterLast()) {
int id=result.getInt(0);
String name=result.getString(1);
int inventory=result.getInt(2);
// do something useful with these
result.moveToNext();
}
result.close();
In the above code example, some of these common methods have been used. For more information, you can refer to the instructions in the official documentation.
Finally, when we have completed the operation on the database, remember to call the close() method of SQLiteDatabase to release the database connection, otherwise SQLiteException is prone to occur.
The above is the basic application of SQLite, but in actual development, in order to better manage and maintain the database, we will encapsulate a database operation class that inherits from the SQLiteOpenHelper class, and then encapsulate our business logic method based on this class. .