We talked about how to store data in files before, so apart from this method, it is common to store data in databases that everyone knows.
Advantages of storing data in a database:
1) The data stored in the database is more convenient to operate, such as adding, deleting, modifying, checking, etc.
2) The rollback of transactions can be realized, such as bank transfers, etc.
3) Easy maintenance and high readability
4) Low resource usage and high performance
5)……
SQLite databases are missing everywhere in our daily life, such as our mobile phones ~ mobile phones on the market now use SQLite databases as data storage.
And the smart homes we often see also use SQLite databases to record data. And the desktop programs we often use, such as QQ, Thunder, etc.
1. The concept and advantages and disadvantages of SQLite database
The SQLite database is an open source embedded database engine, and each of its databases exists in the form of a single file
These data are stored on the disk in the form of B-Tree data structure.
The SQLite database is a small file that can be opened and run directly, while other databases are a large application.
Advantages of using SQLite:
1. SQLite supports most sql standard statements
Add, delete, modify, check, transaction, etc., so I won’t talk about this in detail here...
2. Lightweight
It can be said to be pocket-sized, but the small SQLite can support databases up to 2TB in size
3. Fast search speed
4. Dynamic data model (weak type)
SQLite database support
NULL: empty value
INTEGER: integer type
REAL: floating point
TEXT: string text
BLOB: binary object
5 basic data types.
The reason why it is called "weak type" is that no matter what data type it is, it will be automatically converted when inserting data.
Note: When the constraint of INTEGER is PRIMARY KEY, it must be an integer and will not be automatically converted, otherwise an error will be reported!
5. The SQLite database does not need to be installed and configured before use, nor does it need to enable the process to start and close the database
6. Occupies less system resources
7. Cross-platform
It can be used under multiple operating systems without the need to write code independently for a certain operating system, that is to say, its data layer is the same in each operating system;
At the same time, it is also determined by the internal mechanism of the SQLite database. The SQL database runs on the SQLite virtual machine.
On the virtual machine, it will be directly translated and compiled into data models of different operating systems.
The disadvantages of SQLite are:
1. Does not support large projects
2. Some SQL standard statements are not supported, but these statements are generally not used...
3. Compared with other large databases, the security is poor
Compared with our Android phones, as long as you get root permissions, it proves that you can do whatever you want...
So how does Android strengthen its security?
a. Improve program security verification
b. Strengthen the rigor of the code
c. Authority management
Due to the advantages of the SQLite database, many desktop applications use it to store the data of the application;
Of course, our Android and iPhone product chains almost all use SQLite databases.
2. Implementation in Android
1. Use native methods to perform simple operations on the database
That is, write SQL code directly
a. Define a method and inherit the SQLiteOpenHelper class. And implement the onCreate and onUpgrade methods, and override the custom methods.
Override custom methods:
1) There are many parameters, so here simply only need the context parameter.
2) super parameters:
context: context
name: database name
factory: the purpose of creating cursor objects
version: database version, generally starting from 1
onCreate method:
1) It is used when the database is created for the first time, if it is second, it is opened
2) Suitable for initialization of table structure
onUpgrade method:
1) Used when the version of the database is upgraded
2) Suitable for updating the table structure
execSQL:
The sql statement to be executed is suitable for addition, deletion, and modification
public class MyOpenHelper extends SQLiteOpenHelper { /** * * @param context context * name name of database * factory purpose to create cursor object * version database version starts from 1 */ public MyOpenHelper(Context context) { super(context, "test_1.db ", null, 3); } /** * When the database is created for the first time * This method is especially suitable for initializing the table structure. Creating a table is to write a sql statement */ @Override public void onCreate(SQLiteDatabase db) { db. execSQL("create table test_info(id integer primary key autoincrement,name varchar(20))"); } / ** * Used when the database version is upgraded * This method is suitable for updating the table structure */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("alter table test_info add phone varchar(20)"); } }
b. Attention must be paid to the downgrade onDowngrade of the database, the key design points of downgrade
1) Consider the cloud to save users [custom data, behavior habits]. Professional term profile–>> improve user viscosity
2) Consider the current minimum version requirements –>> reduce maintenance costs
3) Local data transfer as much as possible (all new versions do not delete fields) –> turn unknowns into knowns as much as possible
4) The downgrade is likely to fail, so we generally try-catch ; when the downgrade is successful, it is the statement of the try block, and the statement of the catch block is executed after the failure
5) SQLiteDatabase (execution statement), oldVersion (old version number), newVersion (new version number)
/* The simulation will decrease from 3.0 to 2.0 */ @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { //Normally speaking, if it is greater than 2.0, there should be a test_info table, and the fields in 2.0 are all in 3.0 Yes try { //First, first rename the future table of test_info String rename_sql = "alter table test_info rename to test_info_bak"; db.execSQL(rename_sql); Log.i("down", "1. Renamed successfully") ; //Second, create a 2.0 table structure String sql_message = "create table test_info (id int primary key, tou1 varchar(50), userName varchar(50),
lastMessage varchar(50), datetime varchar(50))"; db.execSQL(sql_message); Log.i("down", "2.Create 2.0 table structure successfully"); //Third, copy the backup data to the newly created 2.0 table String sql_copy = "insert into test_info select id,tou1,userName,lastMessage,datetime from test_info_bak"; db.execSQL(sql_copy); Log.i(" down", "3.copy user data to 2.0 table"); //Fourth, drop the backup table String drop_sql = "drop table if exists test_info_bak"; db.execSQL(drop_sql); Log.i(" down", "4. Drop the backup table"); } catch (Exception e) { //Failure Log.i("hi", "Downgrade failed, re-establish"); String sql_drop_old_table = "drop table if exists test_info "; String sql_message = "create table test_info(id integer primary key autoincrement,name varchar(20),phone varchar(20))"; String sql_init_1 = "insert into test_info values (1,'abc','130000')"; String sql_init_2 = "insert into test_info values (2,'abc','134444')"; db.execSQL(sql_drop_old_table); db.execSQL(sql_message); db.execSQL(sql_init_1); db.execSQL(sql_init_2); } }
c. Create a MyOpenHelper object
myOpenHelper = new MyOpenHelper(getApplicationContext()); //Open or create a database if it is created for the first time, then open //SQLiteDatabase sqliteDatabase = myOpenHelper.getWritableDatabase(); //Open or create a database if it is the first time Create, followed by opening and returning read-only if the disk is full //SQLiteDatabase sqliteDatabase = myOpenHelper.getReadableDatabase();
d. Increase data
//Get the database object SQLiteDatabase db = myOpenHelper.getWritableDatabase(); //Execute and add a sql statement db.execSQL("insert into test_info(name,phone) values(?,?)",new Object[]{"zhangsan" ,"138888888"}); // close the database when it is used up db.close();
e. Delete data
SQLiteDatabase db = myOpenHelper.getWritableDatabase(); db.execSQL("delete from test_info where name=?",new Object[]{"zhangsan"}); db.close();
f. Modify data
SQLiteDatabase db = myOpenHelper.getWritableDatabase(); db.execSQL("updata test_info set phone=? where name=?",new Object[]{"13777777777","zhangsan"}); db.close();
g. Query data
SQLiteDatabase db = myOpenHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from test_info", null); if(cursor!=null&&cursor.getCount()>0){ while(cursor.moveToNext()){ //columnIndex代表列的索引 String name = cursor.getString(1); String phone = cursor.getString(2); } }
2. Use the API packaged by Google to perform simple operations on the data
Google engineers have packaged some methods for us to call directly, but in fact, at the bottom layer, these strings are spliced into complete SQL statements.
a. Increase data
A map collection encapsulated inside ContentValues, which stores data in the form of <key, value>.
insert parameter description
table: table name
key: the name of the corresponding column
value: the corresponding value
put parameter description
key: the added column name
value: the corresponding value
//Get the database object SQLiteDatabase db = myOpenHelper.getWritableDatabase(); /** * table table name * ContentValues encapsulates a map inside * key: the name of the corresponding column * value: the corresponding value */ ContentValues values = new ContentValues(); values.put("name", "wangwu"); values.put("phone", "120"); //The return value represents the id of the new row inserted long insert = db.insert("test_info", null, values );//The bottom layer is splicing SQL statements //Close the database when it is used up db.close(); if(insert>0){ Toast.makeText(getApplicationContext(), "Added successfully!", 3000).show() ; }else{ Toast.makeText(getApplicationContext(), "Failed to add!", 3000).show(); }
b. Delete data
delete parameter description
table: table name
whereClause: Which column to delete, according to what to delete
whereArgs: What is returned here is an array object, according to the value of the deleted column
SQLiteDatabase db = myOpenHelper.getWritableDatabase(); //Delete according to Google's packaged api int delete = db.delete("test_info", "name=?", new String[]{"wangwu"}); db.close( ); Toast.makeText(getApplicationContext(), "Deleted "+delete+" line", 2000).show();
c. Modify data
update parameter description
table: table name
value: is the value in ContentValues
whereClause: Which column to modify, according to what modification
whereArgs: Here is an array object, according to the value of the modified column
SQLiteDatabase db = myOpenHelper.getWritableDatabase();
//Modify ContentValues according to Google's packaged api value = new ContentValues(); value.put("phone", "110"); //Represents how many rows have been updated int updata = db .update("test_info", value, "name=?", new String[]{"wangwu"}); db.close(); Toast.makeText (getApplicationContext(), "updated"+updata+"line", 2000).show();
d. Query data
query parameter description
table: table name
columns: the columns of the query
selection: according to what query
selectionArgs: the value of the query condition
groupBy: grouping
having: query conditions, here we need to distinguish the difference between having and where!
orderBy: sort
moveToNext(): traverse the data in the data table
cursor: the pointer object encapsulated by Google engineers, used to traverse the collection subscript
SQLiteDatabase db = myOpenHelper.getWritableDatabase(); /** * Query based on Google's packaged api * columns represent the columns you want to query * selection Query phone based on what */ Cursor cursor = db.query("test_info", new String[ ]{"phone"}, "name=?", new String[]{"wangwu"}, null, null, null); if(cursor!=null &&cursor.getCount()>0){ while(cursor.moveToNext( )){ String phone = cursor. getString(0); System. out. println("phone:" + phone); } }
3. Advantages and disadvantages of using native methods and packaged api methods
a. Advantages of native methods
1) You can use sql statements more flexibly
2) The amount of code can be reduced and the efficiency is higher
b. Disadvantages of native methods
1) It is easy to write wrong sql code
2) Not easy to maintain
c. Advantages of good packaging
1) There is no need to write sql statements directly, which reduces the probability of errors
2) Easy maintenance
d. Disadvantages of good packaging
1) Make the program more cumbersome and less efficient
2) It is inconvenient to operate data, and cannot flexibly use data operation statements
No matter which method is used, it has its advantages and disadvantages, so in actual development, it depends on the actual situation, and any method you want to use is also feasible.
Suggestion: For smaller programs, it is recommended to use packaged APIs, which are relatively simple and can improve development efficiency
It is recommended to use native methods for relatively large programs, which are more flexible and can also improve program efficiency
3. Summary
1. Advantages and disadvantages of using SQLite
2. Database upgrade and downgrade (*****)
3. Use native methods to perform simple operations on the database
4. Use the API packaged by Google to perform simple operations on the database
5. Advantages and disadvantages of each
6. The data layer of the Android and iPhone product chains is the same
ps: Interested students can think about WeChat:
How is SQLite implemented on the client side?
What is used to achieve it in the background server, and how is it achieved?
So what about the interaction of these data?
How to optimize it?