1. What is SQLite?
SQLite is an in-process library that implements a self-sufficient, serverless, zero-configuration, transactional SQL database engine. It is a zero-configuration database, which means that unlike other databases, you do not need to configure it in the system. Like other databases, the SQLite engine is not a stand-alone process and can be statically or dynamically linked according to application needs. SQLite directly accesses its storage files.
2. Features of SQLite
Lightweight, no configuration required, localized
3. Create a database
Create a new class and inherit SQLiteOpenHelper
Implement two abstract methods onCreate() onUpgrade() Create a constructor with parameters
Create database in constructor
In the onCreate() method, create the table and insert data
In the mobile phone, use the package name to identify the software's
SQLite data type
type | SQLite | Java |
---|---|---|
integer | INTEGER | byte, short, int, long |
floating point | REAL | float, double |
string | TEXT | String |
boolean string | BLOB | boolean |
3. SQLite CRUD
1. Query (there are three methods for receiving result sets: List<Object[ ]>, List<entity class>, List<Map<String,int>>)\
Using entity class method:
SQLiteDatabase db = dbHelper.getWritableDatabase();
List<User> list = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from user_table");
while (cursor.moveToNext()) {
String account = cursor.getString(cursor.getColumnIndex("account"));
String pwd= cursor.getString(cursor.getColumnIndex("pwd"));
list.add(res);
}
cursor.close();
return list;
2. Update (addition, deletion, modification)
SQLiteDatabase db = dbHelper.getWritableDatabase();
//删除
db.execSQL(""delete from test where account = ?", new String[]{String.valueOf('123')}");
//增加
db.execSQL("insert into test values(?,?)",new String[]{account,pwd});
//修改
db.execSQL("update test set pwd= ? where account= ?", new String[]{"456",String.valueOf(132)});