当前位置:网站首页>[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);
}
边栏推荐
- Talk about the cloud deployment of local projects created by SAP IRPA studio
- A JS script can be directly put into the browser to perform operations
- 招标公告:盘锦市人民医院盘锦医院数据库维保项目
- Bidding announcement: Panjin people's Hospital Panjin hospital database maintenance project
- Power of leetcode-231-2
- 喜讯!科蓝SUNDB数据库与鸿数科技隐私数据保护管理软件完成兼容性适配
- Odoo integrated plausible embedded code monitoring platform
- hellogolang
- Wireless sensor networks -- ZigBee and 6LoWPAN
- Vs tool word highlight with margin
猜你喜欢

Power of leetcode-231-2
![Unity drawing plug-in = = [support the update of the original atlas]](/img/b0/92114ffb1f168a1f27125db46c6797.jpg)
Unity drawing plug-in = = [support the update of the original atlas]

Shandong old age Expo, 2022 China smart elderly care exhibition, smart elderly care and aging technology exhibition

Numpy -- data cleaning

Statistical learning method -- perceptron

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

Description of vs common shortcut keys
Notification uses full resolution

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

模仿企业微信会议室选择
随机推荐
Xingruige database was shortlisted as the "typical solution for information technology application and innovation in Fujian Province in 2021"
asyncio 概念和用法
Excessive dependence on subsidies, difficult collection of key customers, and how strong is the potential to reach the dream of "the first share of domestic databases"?
Mysql database backup script
Laravel5.1 路由 -路由分组
Bidding announcement: Panjin people's Hospital Panjin hospital database maintenance project
Application example of infinite list [uigridview]
华东师大团队提出,具有DNA调控电路的卷积神经网络的系统分子实现
js中复选框checkbox如何判定为被选中
Is it reliable to open an account on Tongda letter with your mobile phone? Is there any potential safety hazard in such stock speculation
Introduction to pyGame games
目标跟踪常见训练数据集格式
Leetcode-136-只出现一次的数(用异或来解答)
Tragedy caused by deleting the console statement
PHP realizes wechat applet face recognition and face brushing login function
laravel构造函数和中间件执行顺序问题
企业级日志分析系统ELK
A JS script can be directly put into the browser to perform operations
Iptables only allows the specified IP address to access the specified port
记一次项目的迁移过程