当前位置:网站首页>Android section 13 detailed explanation of 03sqlite database
Android section 13 detailed explanation of 03sqlite database
2022-07-24 15:05:00 【Xiayu_】
One 、SQLite Database Overview
1.1SQLite Is an embedded database engine
Compared with other database engines , for example SQL Server、PostgreSQL、MySQL perhaps Oracle,SQLite The most important difference is that it is not designed to replace this type of database system .SQLite Is a database engine embedded in the application , There is no server , There is no separate server process that manages the database . Applications interact with database engine processes through function calls , Instead of sending messages to individual processes or threads .
client / Server database is very important for modern application system , They focus on scalability 、 concurrency 、 Centralized management and control, etc , It solves the problem of shared storage of enterprise data . SQLite It is dedicated to providing local data storage for individual applications and devices , The emphasis is on the economy 、 efficiency 、 reliability 、 Independence and simplicity .
1.2SQLite and Mysql Database storage differences
for instance , Let's say a app,app Where does the data come from , Before we talked about getting from the Internet , Netlog access is actually obtained through a server , Where does the data of the server come from ? Because the server itself is just an application , This application needs to query data , The server itself will install a database , The database installed on the server , It can be what we often use MySQL,Oracle This kind of database , The server is usually a windows System or Linux The computer of the system ,app Send a request to the server , The server then queries the data in the database , Then return the data to app, Like the database used by the server to query , Generally, all users' data is stored , So there will be a lot of data stored , But only the data of the corresponding user will be returned , Not all will be returned to the user , and app After receiving the data , Will do a cache locally , Caches such as pictures will be stored in files , Data with flag bits will exist sp, And like qq This kind of message record cache usually exists SQLite database
Two 、SQLite How to use the database
2.1SQLite Grammar use
frequently-used SQLite sentence :
(id,age For field ,user Is the name of the watch )
1. add to
insert into user(xx varchar(20),xxx Integer)values(?,?)
2. Delete
delete from user where id=?
3. modify
update user set age=? where id=?
4. Inquire about
select * from user where id=?
5. Build table
create table user(id integer primary key autoincrement,
name varchar(50),
sex varchar(20),
date varchar(50),
content varchar(100),
age integer)
2.2SQLite usage
stay java in , When loading the driver, you should consider MySQL still Oracle database , Different databases should be loaded jar package , however SQLite This is his kind , So in Android , A lot of work has been done to load the driver , Android provides a class , The name of this class is SQLiteOpenHelper Helper classes
1. Create a table
This class is an abstract class , It can help us load the driver , But it is an abstract class , We know , Abstraction cannot be used directly , If we want to use it, we must first implement its abstract method , The premise of implementing its abstract method is that we first create a class to inherit this class
First step , First create a class , And then inherit SQLiteOpenHelper This class , And implement abstract methods 

Then create a constructor 
And then in Oncreat Create a table in the method 
Core code :
package com.hnucm.a_test132;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create tables in this method
String sql="create table user(id integer primary key autoincrement,name varchar(50), sex varchar(20),age integer)";
db.execSQL(sql);// This step completes loading the driver and establishing the connection
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
go back to activity
SQLiteOpenHelper The constructor format of class is
public SQLiteOpenHelper(Context context,
String name,
SQLiteDatabase.CursorFactory factory,
int version)
among , Parameters context Represents the context used to open or create data ;name The database file is specified ;factory Used to create cursor object , If you use the default factory, Then set the parameter to null;version Indicates the version number of the database , The version number is from 1 Start increasing in sequence .

2. View table
Android in SQLite Database view recommendation blog 《Android Studio see SQLite Database method Encyclopedia 》
First step : Export simulator database file
find data In the catalog —>data Catalog —> Package name —>databases The database file under the folder 

Right click to save to local 
Save to the specified location 
The second step : Look at the database file
( Open the saved in the first step db file )
Here use Navicat Premium 15 Tools to view

Set up the connection first 
Find the saved in the first step db file location 
see 
Add :
Then modify the database table ( For example, add, delete, change, check ) in the future , You need to right-click to close the database , Then repeat the first and second steps above
3. Add data
First step , Let's add a... To the layout file first button
The second step , Add click event 
We first see insert This method needs to pass three values , The first is the database table name , Pass the second one null It's worth it ok, The third one ContentValues We can regard it as a HashMap, Although the function is similar
The third step , adopt insert Add data to the database table 
package com.hnucm.a_test132;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteOpenHelper mySQLiteOpenHelper=
new MySQLiteOpenHelper(this,"users.db",null,1);
// // Read the database Inquire about
// SQLiteDatabase sqLiteOpenHelper=mySQLiteOpenHelper.getReadableDatabase();
// Write to the database Additions and deletions
SQLiteDatabase sqLiteDatabase=mySQLiteOpenHelper.getWritableDatabase();
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("name"," Han Han ");
contentValues.put("sex"," male ");
contentValues.put("age",20);
sqLiteDatabase.insert("user",null,contentValues);
}
});
}
}
Step four , see sqlite database
The first step is to shut down the database , Step 2 and then re Export db file , Step 3: open the corresponding db File database



4. Delete data
Here we need to use the method delete
Let's see delete The value that the method needs to pass
The first value is the table name , Second value whereClause Is the condition that the data meets ( such as id=1), The third value is passed to the second value String Data of type
First step : increase button Button 
The second step : Write logic code 
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sqLiteDatabase.delete("user","id=?",new String[]{"2"});
}
});
The third step : Rerun ( Follow these steps )
If we want to delete , Deleting data requires several conditions
It can be used and Represents data that meets multiple conditions at the same time 
//id=2 also name= Han Han's data
sqLiteDatabase.delete("user","id=? and name=?",new String[]{"2"," Han Han "});
It can be used or Represents data that satisfies one of several conditions 
//id=2 perhaps name= Han Han's data
sqLiteDatabase.delete("user","id=? or name=?",new String[]{"2"," Han Han "});
5. Modifying data
Here we need to use the method update, This method needs to pass four values ,
The first value is the table name . The second value is similar to that mentioned before HashMap Of ContentValues, Third values whereClause Is the condition that the data meets ( such as id=1), The fourth value is passed to the third value String Data of type
adopt ContentValues Add new data after modification , Then modify the data according to the conditions that the data meets

ContentValues contentValues=new ContentValues();
contentValues.put("name"," Sweet Coca ");
contentValues.put("sex"," Woman ");
contentValues.put("age",22);
sqLiteDatabase.update("user",contentValues,"id=?",new String[]{"1"});
Data before modification :
Modified data :
6. Query data
Here we need to use query Method to query , Here we need to pass seven values , The first is the table name , Second value columns Represents the column we want to query ( We have id,name,sex Wait for multiple columns , We can return the columns we want to query as needed ), We can also pass one null Indicates that all fields are returned , Third values selection Indicates the conditions we need to meet to query data ( Similar to the previous whereClause), If you pass one here null value , It is equivalent to returning all data , The fourth value means that it is passed to the third value String Data of type , hinder groupBy grouping ,having Or is it orderBy You can specify some complex query conditions with , If you don't come by group, you will send one null

cursor In the first row, get the data by moving the cursor
Add here : We finally need to close cursor, Prevent memory leaks

Cursor cursor=sqLiteDatabase.query("user",null,"sex=?",new String[]{" male "},null,null,null);
while (cursor.moveToNext()){
int id =cursor.getInt(0);
String name=cursor.getString(1);
String sex=cursor.getString(2);
int age =cursor.getInt(3);
Log.i("Main"," id:"+id+" name:"+name+" sex:"+sex+" age:"+age);
}
cursor.close();
Before query ( I added a few more pieces of data )
Query results :
About SQLite Let's talk about the database first , Thank you for reading , Next, I will talk about a more convenient method
边栏推荐
- Simple understanding and implementation of unity delegate
- CSDN garbage has no bottom line!
- Differences between C language pointer and array A and &a, &a[0], etc
- (零九)Flask有手就行——Cookie和Session
- 多数据源配置下,解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题
- pip换源
- The sliding window of Li Kou "step by step" (209. The smallest sub array, 904. Fruit baskets)
- Number of bytes occupied by variables of type char short int in memory
- Simple encapsulation of wechat applet wx.request
- Spark Learning Notes (III) -- basic knowledge of spark core
猜你喜欢
![[USENIX atc'22] an efficient distributed training framework whale that supports the super large-scale model of heterogeneous GPU clusters](/img/dc/be4dc55cdf3085a7b9e58ed6d6a16e.png)
[USENIX atc'22] an efficient distributed training framework whale that supports the super large-scale model of heterogeneous GPU clusters

多数据源配置下,解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题

REST风格

The server switches between different CONDA environments and views various user processes

Rest style
![[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes](/img/4d/b0ba599a732d1390c5eeb1aea6e83c.png)
[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes

spark:获取日志中每个时间段的访问量(入门级-简单实现)

打假Yolov7的精度,不是所有的论文都是真实可信

《Route planning method for UAV in unknown environment based on improved SAS algorithm》翻译

Detailed explanation of document operation
随机推荐
野火stm32霸道,通过固件库实现流水灯
"After 00" is coming! Digital data ushers in a new generation of "codeless" forces
Summary of Baimian machine learning
Rasa 3.x learning series -rasa [3.2.4] - 2022-07-21 new release
Intelligent operation and maintenance scenario analysis: how to detect abnormal business system status through exception detection
Atcoder beginer contest 261 f / / tree array
onBlur和onChange冲突解决方法
DDD based on ABP -- Entity creation and update
异或程序
Isprs2018/ cloud detection: cloud/shadow detection based on spectral indexes for multi/hyp multi / hyperspectral optical remote sensing imager cloud / shadow detection
关于构建网络安全知识库方向相关知识的学习和思考
A common Dao class and util
Simple understanding and implementation of unity delegate
PrestoUserError: PrestoUserError(type=USER_ERROR, name=INVALID_FUNCTION_ARGUMENT, message=“Escape st
LeetCode高频题56. 合并区间,将重叠的区间合并为一个区间,包含所有区间
zabbix管理员忘记登录密码
Learning and thinking about the relevant knowledge in the direction of building network security knowledge base
Kali concise language transformation method (illustration)
循环结构practice
Production environment tidb cluster capacity reduction tikv operation steps





