当前位置:网站首页>[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);
}
边栏推荐
- What are compiled languages and interpreted languages?
- Notification uses full resolution
- Laravel5.1 路由 -路由分组
- Xcode Revoke certificate
- Eye of depth (VII) -- Elementary Transformation of matrix (attachment: explanation of some mathematical models)
- 【C 语言】 题集 of Ⅹ
- Step by step monitoring platform ZABBIX
- AE learning 02: timeline
- 统计学习方法——感知机
- 分步式監控平臺zabbix
猜你喜欢

喜讯!科蓝SUNDB数据库与鸿数科技隐私数据保护管理软件完成兼容性适配

MySQL数据库基本操作-DQL-基本查询

【C 语言】 题集 of Ⅹ

【Android -- 数据存储】使用 SQLite 存储数据

HAVE FUN | “飞船计划”活动最新进展

Lecturer solicitation order | Apache seatunnel (cultivating) meetup sharing guests are in hot Recruitment!

Enterprise log analysis system elk

Leetcode-231-2的幂

spark调优(三):持久化减少二次查询

Unity3d click events added to 3D objects in the scene
随机推荐
spark调优(三):持久化减少二次查询
【Vulnhub靶场】THALES:1
Unity3D_ Class fishing project, control the distance between collision walls to adapt to different models
PHP realizes wechat applet face recognition and face brushing login function
华东师大团队提出,具有DNA调控电路的卷积神经网络的系统分子实现
torch.numel作用
Introduction to ThinkPHP URL routing
Laravel constructor and middleware execution order
How to determine whether the checkbox in JS is selected
The inevitable trend of the intelligent development of ankerui power grid is that microcomputer protection devices are used in power systems
A link opens the applet code. After compilation, it is easy to understand
thinkphp3.2.3中设置路由,优化url
Bidding announcement: Fujian Rural Credit Union database audit system procurement project (re bidding)
用手机在通达信上开户靠谱吗?这样炒股有没有什么安全隐患
融云斩获 2022 中国信创数字化办公门户卓越产品奖!
AE learning 01: AE complete project summary
PHP实现微信小程序人脸识别刷脸登录功能
目标跟踪常见训练数据集格式
What about the pointer in neural network C language
Continuous creation depends on it!