Objective
AndroidThere are many ways to store data in, where using a SQLite database is the best choice for storing structured data. Fortunately, the Android support is provided by default in SQLite , which makes it Android particularly convenient to use the SQLite database in.
Supported data types
SQLite is a lightweight database that supports a very simple data type, mainly in the following ways:
- Text: Character type
- Real: floating-point type
- Integer: int type
- BLOB: Binary data type
Create a database
SQLiteThe use of the database starts with SQLiteOpenHelper this abstract class. We need to customize the class to inherit and SQLiteOpenHelper rewrite it 构造方法 . In fact, there are two constructor methods that can be overridden, and generally we choose the one that has fewer parameters to rewrite.
In addition, we also need to implement and both of onCreate onUpgrade these abstract methods. In the onCreate method, we create the database. In the onUpgrade method, we upgrade and update the database. The basic code is as follows:
public class BookOpenHelper extends SQLiteOpenHelper{ private static final String CREATE_BOOK="create table Book(" + "id integer primary key autoincrement," + "name text," + "price text," + "author text)"; public BookOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BOOK); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }}
As you can see, in the constructor method, we simply call the constructor of the parent class. In the constructor's argument list, the first parameter is the Context object, the second parameter is the database name, the third parameter is generally passed in null , and the fourth parameter is the version number of the database.
In addition, we define a string constant. Obviously, this is a built-in statement to create a Book table named. In this table, we have defined four fields, respectively id、name、price、author . Where, id by primary key and autoincrement modifying, represents that it is the primary key of the table and is self-increasing. In the onCreate method, we call the SQLiteDatabase execSQL method that executes the Book table's build statement.
In practical use, we need to build SQLiteOpenHelper the instance first, then call it getReadableDatabase or the getWritableDatabase method, and if the database is not yet created, the system creates the database and invokes SQLiteOpenHelper the onCreate method. The instance code is as follows:
BookOpenHelper dbOpenHelper=new BookOpenHelper( MainActivity.this,"SQLiteDemo.db",null,1);dbOpenHelper.getReadableDatabase();
getReadableDatabaseAnd getWritableDatabase methods return an object that can be used for the database to be added and checked SQLiteDatabase . The difference is that when the phone storage space is full, the former will return null, the latter will throw an exception.
Update Database
In actual development, it is often necessary to modify the database, such as adding new tables or adding table fields. To implement an update to the database, we need to pass in a version parameter that is larger than the current version number when building the sqliteopenhelper instance, which results in the The Onupgrade method of the Sqliteopenhelper is called. In this method, we can do the update operation of the database. The following code demonstrates adding a table named Author in the previous database:
public class Bookopenhelper extends sqliteopenhelper{...//Create author table private static final String create_author= "CREATE TABLE AUTHOR (" + "ID integer primary key autoincrement," + "Name text," + "Age integer"); Public Bookopenhelper (Context context, String name, Sqlitedatabase.cursorfactory factory, int version) {SUPER (cont EXT, name, factory, version); } @Override public void OnCreate (Sqlitedatabase db) {db.execsql (Create_book); Db.execsql (Create_author); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {switch (oldversion) { Case 1:db.execsql (Create_author); Default:break; } }}
We have defined a new string constant to CREATE_AUTHOR create the Autho r table. At the same time, we also implemented in the onCreate method db.execSQL(CREATE_AUTHOR); . If the app is installed for the first time, you can create two tables normally. However, if the app was already installed before. The onCreate method will not be executed because the database already exists. In this case, we write the remedial measures in the onUpgrade method. With the oldVersion judgment of the old version number, we execute the subsequent statement of the build table. As long as the SQLiteOpenHelper parameters that are larger than the current version number are passed in when they are created, the method is version onUpgrade called and the table is Author created.
What if we now want to Author add a new field to the table to country record the author's name? In practice, as before, you only need to onUpgrade perform the update operation in the method, with the following code:
public class Bookopenhelper extends sqliteopenhelper{...//Add a new field to the author table private static final St Ring alter_author= "ALTER table AUTHOR Add column country text"; Public Bookopenhelper (Context context, String name, Sqlitedatabase.cursorfactory factory, int version) {SUPER (cont EXT, name, factory, version); } @Override public void OnCreate (Sqlitedatabase db) {db.execsql (Create_book); Db.execsql (Create_author); Db.execsql (Alter_author); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {switch (oldversion) { Case 1:db.execsql (Create_author); Case 2:db.execsql (Alter_author); Default:break; } }}
In the onCreate method, we perform each operation sequentially SQL so that all tables can be created normally when the app is first installed. In the onUpgrade method, we determine which update operation should be done by judging the version number of the current database. If the current version number is 2 , you only need to add a new field to the table, and Author if the current version number is 1 , you need to create the Author table first and then Author add a new field to the table. This is why each is case not added break in order to ensure that the application cross-version upgrade will be able to perform all the update operations in turn. This is especially important to note.
Basic operations
Solves the problem of how to create a database and update the database, and then it can be formally contacted SQLite in the data operation. Generally referred to as the CRUD operation, that is, adding and deleting changes. First, we need to get an SQLiteDatabase object that encapsulates a variety of data manipulation methods. SQLiteOpenHelperThis object can be obtained through an instance getReadableDatabase or getWritableDatabase method.
SQLiteDatabase database=dbOpenHelper.getWritableDatabase();SQLiteDatabase database=dbOpenHelper.getReadableDatabase();
Add data
SQLiteDatabaseBy insert means of the method to add data, its prototype is as follows:
public long insert(String table, String nullColumnHack, ContentValues values)
insertThe method needs to pass in three parameters, the first parameter is the table name, the second parameter is generally passed null in, and the third parameter is an ContentValues object. ContentValuesstores the data that needs to be written to the table by means of key-value pairs. When the insert is complete, this method also returns the number of the inserted data in the table id and returns if the insert fails -1 . The sample code is as follows:
SQLiteDatabase database= dbOpenHelper.getWritableDatabase();ContentValues values=new ContentValues();values.put("name","Android");values.put("author","Bill");values.put("price","60");database.insert("Book",null,values);values.clear();values.put("name","Java");values.put("author","Tom");values.put("price","50");database.insert("Book",null,values);
As you can see, we ContentValues Book have added two data to the table through the same object. Note that the method that you should call before you add the second data ContentValues clear clears the old data.
Querying data
SQLiteDatabaseBy query means of the method to achieve the addition of data, the common version of the method prototype is as follows:
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
queryMethod needs to pass in 7 a parameter. The first parameter is the name of the table. The second parameter is the name of the column that needs to be queried, and if passed in, null all columns are queried. The third parameter and the fourth parameter are the query criteria that are used to limit the rows of the query, which is equivalent to SQL the portion of the query, where if all rows are passed in to null represent queries. The five parameter is the column name of the grouping, equivalent to SQL the group by part in, if the incoming null representation does not group the results. The sixth parameter is equivalent SQL to the having part in. The seventh parameter is the sorted column name, which is passed in to null indicate the default ordering of the query results.
This method returns the object after the query Cursor is completed, which is a cursor that can be traversed to fetch the queried data. The sample code is as follows:
SQLiteDatabase database= dbOpenHelper.getReadableDatabase();Cursor cursor=database.query("Book",null,null,null,null,null,null);if(cursor.moveToFirst()){ do { Log.d(TAG,cursor.getString(cursor.getColumnIndex("id"))); Log.d(TAG,cursor.getString(cursor.getColumnIndex("name"))); Log.d(TAG,cursor.getString(cursor.getColumnIndex("author"))); Log.d(TAG,cursor.getString(cursor.getColumnIndex("price"))); } while(cursor.moveToNext());}cursor.close();
We passed only query one table name for the method, and all the other parameters were passed in null to represent Book all the data in the query table. For the object returned by this method Cursor , we first call the moveToFirst method to move to the first row of the data. Subsequently, the method is judged in a do-while loop cursor moveToNext true , and the getString data in the table is fetched through the method. getColumnIndexmethod to get the index number that corresponds to the specified column name in the table. This is one of the simplest query operations, and now we're going to try a more restrictive query:
SQLiteDatabase database= dbOpenHelper.getReadableDatabase();Cursor cursor=database.query("Book",new String[]{"name","author"}, "author=?",new String[]{"Tom"},null,null,"name");if(cursor.moveToFirst()){ do { Log.d(TAG,cursor.getString(cursor.getColumnIndex("name"))); Log.d(TAG,cursor.getString(cursor.getColumnIndex("author"))); } while(cursor.moveToNext());}cursor.close();
The purpose of the above code is to query the Book table author for Tom the data, and only query name and the data of author these two columns, and finally return the results based on name sorting. It is important to note that after the query is completed, we should also invoke Cursor the close method that frees the resource.
Update data
SQLiteDatabaseBy query means of the method to add data, its prototype is as follows:
updateMethod needs to pass in 4 a parameter. The first parameter is the name of the table. The second parameter is an ContentValues object that stores the updated data. The third parameter and the fourth parameter are the constraints, all passing null in represents all the data in the Update table. When the update is complete, this method returns the number of rows affected. The sample code is as follows:
SQLiteDatabase database= dbOpenHelper.getWritableDatabase();ContentValues values=new ContentValues();values.put("name","Android Plus");database.update("Book",values,"name=?",new String[]{"Android"});
The above code queries Book all name Android the data in the table and name updates the fields to Android Plus . It is important to note that we only need to ContentValues store the data that needs to be updated in, and do not need to store other unchanging data.
Delete data
SQLiteDatabaseThe method delete implements the deletion of the data by means of the following methods:
public int delete(String table, String whereClause, String[] whereArgs)
deletemethod requires three parameters to be passed in. The first parameter is the name of the table. The second and third parameters are constraints, and if both are passed null in, all data in the table is deleted. The sample code is as follows:
SQLiteDatabase database=dbOpenHelper.getWritableDatabase();database.delete("Book","name=?",new String[]{"Java"});
The above code will delete Book all name Java the data in the table.
Using SQL to manipulate databases
In addition to using a SQLiteDatabase well-encapsulated insert、delete、update、query method for database pruning, we can also use SQL statements to manipulate data directly. Of course, the premise is that the SQL Foundation should be good enough. SQLiteDatabaseprovides execSQL and rawQuery these two methods are used to execute SQL statements directly. The difference is that the latter is used to perform query operations, while the former performs other operations. The common versions of these two methods are prototyped as follows:
public void execSQL(String sql, Object[] bindArgs)public Cursor rawQuery(String sql, String[] selectionArgs)
The sample code is as follows:
//插入数据database.execSQL("insert into Book(name,price,author) values(?,?,?)",new String[]{"book","110","Bill"});//查询数据Cursor cursor=database.rawQuery("select * from Book",null);
Using transactions
In Sqlitedatabase, Android also integrates transactional capabilities for developers. So what is a business? Imagine a scenario in which we need to delete some of the data and insert the new data because of the updated version of the app. However, both the delete operation and the insert operation must be successful together, or they will fail together. This avoids the problem of applying errors after deleting the data, causing the insert to fail, affecting the user's normal use. This requirement can be successfully accomplished by using transactions. The sample code is as follows:
SQLiteDatabase database=dbOpenHelper.getWritableDatabase();database.beginTransaction();try{ database.delete("Book","name=?",new String[]{"Android"}); if(true){//手动抛出异常演示在执行事务的过程中操作失败 throw new Exception("手动抛出异常"); } ContentValues values=new ContentValues(); values.put("name","Java"); values.put("author","Jimmy"); values.put("price","500"); database.insert("Book",null,values); database.setTransactionSuccessful();}catch(Exception e){ Log.d(TAG,"执行事务过程中出现错误!"); e.printStackTrace();}finally { database.endTransaction();}
As you can see, we first called SQLiteDatabase the beginTransaction method to open the transaction. Then in the try statement block, we first delete Book all the data in the table name Android , and then Book insert a new data into it. At the end of the try statement block, we call SQLiteDatabase the setTransactionSuccessful method that indicates that the transaction executed successfully. But after we delete the data, we manually throw an exception that will cause subsequent additions to fail. In the ordinary case, the final result is that the data is deleted, but the new data is not added successfully. The use of transactions here, after an exception, will also cause the previous delete operation to fail. It is important to note that we also need to invoke the method in the finally statement block to indicate the end of the endTransaction transaction.
To summarize, the key to using a transaction is the following three sentences, which need to be referred to when using transactions.
database.beginTransaction();database.setTransactionSuccessful();database.endTransaction();
Manipulating databases with open source libraries
In addition to manipulating databases through the way this article explains SQLite , we can also leverage the power of open source libraries. such as Litepal, Greendao, Activeandroid, Realm-java, Sqlbrite and so on . For the use of these open source libraries, you can refer to their Github home page, or refer to the following blogs:
Use Litepal to operate the database (dig the pits first, then fill in)
Project Demo
Here are the examples demo : Sqlitedemo
A detailed description of SQLite database storage in Android