当前位置:网站首页>[Android -- data storage] use SQLite to store data
[Android -- data storage] use SQLite to store data
2022-07-07 16:24:00 【Kevin-Dev】
One 、 Preface
stay Android A total of five data storage methods are provided , Respectively :
1. Files: adopt FileInputStream and FileOutputStream Operate on files . Please refer to the blog for specific usage 《Android Learning notes 34: Using files to store data 》.
2. Shared Preferences: It is often used to store data in the form of key value pairs , Save the system configuration information .
3. Content Providers: Data sharing , For data access between applications .
4. SQLite:Android Its own lightweight relational database , Support SQL Language , It's used to store a lot of data , And can use the data 、 to update 、 Maintenance, etc .
5. Network: Store and obtain data through the network .
This blog mainly introduces the first way , adopt SQLite Store the data .
Two 、 actual combat
In project development , We use databases more or less . stay Android in , We usually use SQLite, because Android stay android.database.sqlite The package encapsulates a lot of SQLite Operation of the API.
In the use of SQLite when , I suggest downloading a local SQLite Client to verify the operation , Written locally SQL After the statement runs correctly , Then transfer to Android in . I use it SQLite Expert Personal.
1. Create an inheritance in SQLiteOpenHelper Class , And rewrite onCreate() and onUpgrade() Method .
public class OrderDBHelper extends SQLiteOpenHelper{
private static final int DB_VERSION = 1;
private static final String DB_NAME = "myTest.db";
public static final String TABLE_NAME = "Orders";
public OrderDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// create table Orders(Id integer primary key, CustomName text, OrderPrice integer, Country text);
String sql = "create table if not exists " + TABLE_NAME + " (Id integer primary key, CustomName text, OrderPrice integer, Country text)";
sqLiteDatabase.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
}
This class is mainly used for building databases and tables , So let's create another one OrderDao It is used to process all data operation methods . stay OrderDao Instantiation in OrderDBHelper:
public OrderDao(Context context) {
this.context = context;
ordersDBHelper = new OrderDBHelper(context);
}
Database operation is nothing more than :“ Add or delete check change ”. about “ Additions and deletions ” This kind of operation on table content transformation , We need to call getWritableDatabase() , You can call the general execSQL(String sql) Method or corresponding operation API:insert()、delete()、update() . And yes “ check ”, Need to call getReadableDatabase() , You can't use execSQL The method , Have to use query() or rawQuery() Method .
Add data
- Initialization data
When entering Demo The program , First judge whether there is data in the table , If there is no data in the table , Add some data first . When initializing data , Because there are more data to be added at one time , So the direct adoption is execSQL Method :
db = ordersDBHelper.getWritableDatabase();
db.beginTransaction();
db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (1, 'Arc', 100, 'China')");
db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (2, 'Bor', 200, 'USA')");
db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (3, 'Cut', 500, 'Japan')");
db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (4, 'Bor', 300, 'USA')");
db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (5, 'Arc', 600, 'China')");
db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (6, 'Doom', 200, 'China')");
db.setTransactionSuccessful();
- Insert a new data
We can also use insert(String table,String nullColumnHack,ContentValues values) Method to insert ,ContentValues The internal realization is HashMap, But there are differences between the two ,ContenValues Key Can only be String type ,Value Only basic types of data can be stored , image string,int And so on. , You can't store things like objects :
public ContentValues() {
// Choosing a default size of 8 based on analysis of typical
// consumption by applications.
mValues = new HashMap<String, Object>(8);
}
Use insert() Methods we insert a new piece of data (7, “Jne”, 700, “China”), We generally regard the operation of modifying data as a transaction (Transaction) Handle :
db = ordersDBHelper.getWritableDatabase();
db.beginTransaction();
// insert into Orders(Id, CustomName, OrderPrice, Country) values (7, "Jne", 700, "China");
ContentValues contentValues = new ContentValues();
contentValues.put("Id", 7);
contentValues.put("CustomName", "Jne");
contentValues.put("OrderPrice", 700);
contentValues.put("Country", "China");
db.insertOrThrow(OrderDBHelper.TABLE_NAME, null, contentValues);
db.setTransactionSuccessful();
Delete data
Delete data in addition to execSQL also delete(String table,String whereClause,String[] whereArgs),whereClause
It's to delete the condition ,whereArgs
Is to delete the condition value array .
db = ordersDBHelper.getWritableDatabase();
db.beginTransaction();
// delete from Orders where Id = 7
db.delete(OrderDBHelper.TABLE_NAME, "Id = ?", new String[]{
String.valueOf(7)});
db.setTransactionSuccessful();
Look at the deleted source code , It will assemble the deletion condition and the deletion condition value array :
public int delete(String table, String whereClause, String[] whereArgs) {
acquireReference();
try {
SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
(!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
try {
return statement.executeUpdateDelete();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
Modifying data
Modifying data is very similar to inserting data , Call methods in addition to execSQL It can also be update(String table,ContentValues values,String whereClause, String[] whereArgs)
:
db = ordersDBHelper.getWritableDatabase();
db.beginTransaction();
// update Orders set OrderPrice = 800 where Id = 6
ContentValues cv = new ContentValues();
cv.put("OrderPrice", 800);
db.update(OrderDBHelper.TABLE_NAME,
cv,
"Id = ?",
new String[]{
String.valueOf(6)});
db.setTransactionSuccessful();
Find data
There are two ways to find data , One is public Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit);
, The other is public Cursor rawQuery(String sql, String[] selectionArgs)
.rawQuery It's similar to the above execSQL, No introduction here ,query The parameters in the method are as follows :
- table: The name of the table
- columns: Array of column names
- selection: Conditionals , amount to where
- selectionArgs: Conditionals , Parameters of the array
- groupBy: Group columns
- having: Grouping conditions
- orderBy: Sort columns
- limit: Paging query limit
- Cursor: Return value , It's the result set ResultSet
We can see that the return types are Cursor,Cursor Is a cursor interface , The method of traversing query results is provided , Such as moving pointer method move(), Get column value method .Cursor The common methods of cursors are as follows :
Let's check the user name first "Bor" Information about :
db = ordersDBHelper.getReadableDatabase();
// select * from Orders where CustomName = 'Bor'
cursor = db.query(OrderDBHelper.TABLE_NAME,
ORDER_COLUMNS,
"CustomName = ?",
new String[] {
"Bor"},
null, null, null);
if (cursor.getCount() > 0) {
List<Order> orderList = new ArrayList<Order>(cursor.getCount());
while (cursor.moveToNext()) {
Order order = parseOrder(cursor);
orderList.add(order);
}
return orderList;
}
Of course, we can also check the total 、 Maximum value, minimum value and so on , In the query Country by China For example, the total number of users :
db = ordersDBHelper.getReadableDatabase();
// select count(Id) from Orders where Country = 'China'
cursor = db.query(OrderDBHelper.TABLE_NAME,
new String[]{
"COUNT(Id)"},
"Country = ?",
new String[] {
"China"},
null, null, null);
if (cursor.moveToFirst()) {
count = cursor.getInt(0);
}
边栏推荐
- Laravel post shows an exception when submitting data
- SysOM 案例解析:消失的内存都去哪了 !| 龙蜥技术
- How does laravel run composer dump autoload without emptying the classmap mapping relationship?
- asyncio 概念和用法
- Shader_ Animation sequence frame
- PHP中exit,exit(0),exit(1),exit(‘0’),exit(‘1’),die,return的区别
- 通知Notification使用全解析
- Talk about the cloud deployment of local projects created by SAP IRPA studio
- What about the pointer in neural network C language
- Lecturer solicitation order | Apache seatunnel (cultivating) meetup sharing guests are in hot Recruitment!
猜你喜欢
Multiplication in pytorch: mul (), multiply (), matmul (), mm (), MV (), dot ()
分步式監控平臺zabbix
Xcode Revoke certificate
MySQL数据库基本操作-DQL-基本查询
Shipping companies' AI products are mature, standardized and applied on a large scale. CIMC, the global leader in port and shipping AI / container AI, has built a benchmark for international shipping
Numpy -- data cleaning
Rongyun won the 2022 China Xinchuang digital office portal excellence product award!
Statistical learning method -- perceptron
深度之眼(七)——矩阵的初等变换(附:数模一些模型的解释)
Dotween -- ease function
随机推荐
Logback logging framework third-party jar package is available for free
Laravel service provider instance tutorial - create a service provider test instance
What else can an ordinary person do besides working in a factory to make money?
The differences between exit, exit (0), exit (1), exit ('0 '), exit ('1'), die and return in PHP
Introduction to ThinkPHP URL routing
Laravel 中config的用法
js中复选框checkbox如何判定为被选中
SysOM 案例解析:消失的内存都去哪了 !| 龙蜥技术
[summary of knowledge] summary of notes on using SVN in PHP
Talk about the cloud deployment of local projects created by SAP IRPA studio
Three singleton modes of unity (hungry man, lazy man, monobehavior)
IP地址和物理地址有什么区别
Set the route and optimize the URL in thinkphp3.2.3
TCP framework___ Unity
There are many ways to realize the pause function in JS
Laravel post shows an exception when submitting data
Performance comparison of tidb for PostgreSQL and yugabytedb on sysbench
企业级日志分析系统ELK
Numpy -- data cleaning
Asyncio concept and usage