Four storage methods for Android data: SharedPreferences, SQLite, Content Provider, and File (2) -- SQLite and androidsqlite

Source: Internet
Author: User

Four storage methods for Android data: SharedPreferences, SQLite, Content Provider, and File (2) -- SQLite and androidsqlite

SQLite is a lightweight database designed for embedded devices. It has only five data types:

NULL: NULL

INTEGER: INTEGER

REAL: Floating Point Number

TEXT: String

BLOB: Big Data

In SQLite, the BOOLEAN and DATE types are not specifically designed, because the BOOLEAN type can replace true and false with INTEGER 0 and 1, the DATE type can have TEXT, REAL, and INTEGER values in a specific format instead of display. To facilitate the operation of the DATE type, SQLite provides a set of functions. For details, see http://www.sqlite.org/lang_datefunc.html. This simple data type design is more in line with the requirements of embedded devices. For more information about SQLite, see: http://www.sqlite.org/

The Android. database. sqlite package is provided in the android system for adding, deleting, modifying, and querying SQLite databases. The main method is as follows:

BeginTransaction (): starts a transaction.

Close (): close the connection and release resources.

Delete (String table, String whereClause, String [] whereArgs): delete records that meet the specified conditions.

EndTransaction (): ends a transaction.

ExecSQL (String SQL): Execute the given SQL statement.

Insert (String table, String nullColumnHack, ContentValues values): insert a record based on the given conditions.

OpenOrCreateDatabase (String path, SQLiteDatabase. CursorFactory factory): connects to the database based on the given conditions. If the database does not exist, it is created.

Query (String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy): Execute the query.

RawQuery (String SQL, String [] selectionArgs): executes the query based on the given SQL.

Update (String table, ContentValues values, String whereClause, String [] whereArgs): Modify the records that meet the conditions according to the given conditions.

In addition to the main appeal method, Android also provides many practical methods. In a word, it is very convenient for Android to access the database.

1. Create a database

Use openOrCreateDatabase (String path, SQLiteDatabase. CursorFactory factory) to create a database.

1 SQLiteDatabase db =this.openOrCreateDatabase("test_db.db", Context.MODE_PRIVATE, null);
2 SQLiteDatabase db2 = SQLiteDatabase.openOrCreateDatabase("/data/data/com.test/databases/test_db2.db3", null);

Both of the above methods can create a database, this. openOrCreateDatabase is for SQLiteDatabase. openOrCreateDatabase, as seen in the Code, the native SQLiteDatabase. the first parameter of the openOrCreateDatabase () method requires an absolute path, and all databases are stored in the "data/Application Registration/databases" directory, therefore, completely inputting absolute paths is a repetitive and complex task. Using this. openOrCreateDatabase saves this operation. The result after the operation is executed is as follows:

 

In addition, you can create a database by writing a method that inherits the SQLiteOpenHelper class. This method is a more advanced creation method, so it is not described here.

2. Create a data table and insert data.

The Android system does not provide a special method for creating data tables. The data tables are created using SQL statements. The Code is as follows:

1 db.execSQL("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)");

After the table is created, use the insert (String table, String nullColumnHack, ContentValues values) method to insert data. The parameter meanings are as follows:

Table: name of the target table.

NullColumnHack: Specifies the name of a column in the table. In SQLite, it is not allowed to insert records whose columns are null. Therefore, when the initial value has a null value, this column must be explicitly assigned null

Values: ContentValues object, similar to Map in java. Store data in key-value pairs.

The data insertion code is as follows:

1  ContentValues values =new ContentValues();
2 for(int i=0;i<10;i++){
3 values.put("name", "test"+ i);
4 db.insert("tab", "_id", values);
5 }

 

After this operation is performed, a data table named "tab" is added. The structure and data of this table can be easily viewed using the SQLite client (recommended: SQLite Expert Personal 3. For example:

  

3. modify data

The update (String table, ContentValues values, String whereClause, String [] whereArgs) method is used to modify data. The specific meanings of the four parameters are as follows:

Table: name of the target table.

Values: the new value to be modified.

WhereClause: where clause, excluding the rest of the where keyword, which can contain? Placeholder. If there is no clause, it is null.

WhereArgs: used to replace the whereClause parameter? Placeholder parameters. If you do not need to input a parameter, It is null.

The data modification code is as follows:

1 ContentValues values =new ContentValues();
2 values.put("name", "name");
3 db.update("tab", values, "_id=1", null);
4 db.update("tab", values, "_id=?", new String[]{"5"});

 

The execution result is the data of _ id = 1 and _ id = 5. The value of the name field is changed to "name ".

4. query data.

We have been using the SQLite client to view data. Here we use the query () and rowQuery () methods provided by android to execute the query. The Code is as follows:

 

 1 Cursor c = db.query("tab", null, null, null, null, null, null);
2 c.moveToFirst();
3 while(!c.isAfterLast()){
4 int index = c.getColumnIndex("name");
5 Log.d("SQLite", c.getString(index));
6 c.moveToNext();
7 }
8 c = db.rawQuery("select * from tab", null);
9 c.moveToFirst();
10 while(!c.isAfterLast()){
11 int index = c.getColumnIndex("name");
12 Log.d("SQLite", c.getString(index));
13 c.moveToNext();
14 }

The query result is as follows:

It is clear that in the query results, the data on the red line is completely consistent, that is, the difference between the query and rawQuery methods lies only in the difference of the required parameters. The rawQuery method requires the developer to manually write the query SQL statement. The query method consists of the target table name, where clause, order by clause, having clause, and many other clauses. The two methods return the same Cursor object. Therefore, the two methods are superior to the others when using them, depending on the specific situation. I prefer rawQuery, because it is closer to traditional Java development and can be written by professional DBAs. This is more in line with the MVC idea, and the code is more readable. (There are too many parameters in the query method. I cannot remember who is the order by clause and who is the having clause)

The Cursor object can be understood as a Cursor object. Anyone who has knowledge about the data is sure to be familiar with this object. Note that when reading data from the Cursor object for the first time, you must move the Cursor first. Otherwise, the Cursor is located before the first record, causing an exception.

5. delete data

Deleting data is also very easy. You only need to call the delete method and pass in the parameter, delete (String table, String whereClause, String [] whereArgs) the meanings of the three parameters are as follows:

Table: name of the target table.

WhereClause: where clause, excluding the rest of the where keyword, which can contain? Placeholder. If there is no clause, it is null.

 

WhereArgs: used to replace the whereClause parameter? Placeholder parameters. If you do not need to input a parameter, It is null.

 

The Code is as follows:

db.delete("tab", "_id=? or name=?", new String[]{"8", "name"});

 

The execution result is as follows:

 

 

The _ id = 8 and name = 'name' data are all deleted.

The CRUD operation of the entire database has been demonstrated. The last note is that after the data operation, you must call the close () method to close the connection and release the resource. I believe everyone understands this.

 

Related links:

Four storage methods for Android data: SharedPreferences, SQLite, Content Provider, and File (1) -- Overview

Four storage methods for Android data: SharedPreferences, SQLite, Content Provider, and File (3) -- SharedPreferences

Four storage methods for Android data: SharedPreferences, SQLite, Content Provider, and File (4) -- ContentProvider

 

 

Welcome to Chengdu-Android group:






Blog: http://lyjbk.com


========================================================== ======================================
If you think this blog is useful to you, do not use your mouse to give this blog a "recommendation.

This blog post is original and copyrighted. If you need to reprint it, please enter the reposted address.
Original blog address: wisekingokok.cnblogs.com
========================================================== ======================================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.