Android SQLite, KopDB framework Learning 1 -- use, sqlitekopdb

Source: Internet
Author: User

Android SQLite, KopDB framework Learning 1 -- use, sqlitekopdb
Preface

My blog: http://mrfufufu.github.io/
Databases need to be used in recent projects, because the amount of data that needs to be stored locally is not very large, and SharedPreferences is enough to solve most data storage problems, so we have never used SQLite. Now the product needs to optimize the user experience of the private message module, so it is necessary to increase the private message local storage. At this time, it is necessary to use SQLite. Fortunately, our boss has encapsulated a very well-developed database framework for use. After reading the source code for a day, I learned about it, sorted it out, and learned how to use it.

Name him.KopDB(Kop is the tag used when our boss logs ),KopDBWe use the object relational ing (ORM) mode and encapsulate some of the database functions most commonly used during development, this allows you to create tables and delete and modify tables without having to write a single SQL statement.

This article focuses only on the use of KopDB. For detailed analysis, I will refer to the next article.

Github Project address, which contains lib and corresponding demo. Welcome to Star.

https://github.com/MrFuFuFu/KopDB.git

The main usage is very simple:

The data model in the demo is provided for later reading and understanding:

public class PersonModel extends BaseModel {    private static final long serialVersionUID = 3462436436344054489L;    public static final String PERSON_ID = "person_id";    public static final String PERSON_NAME = "person_name";    public static final String PERSON_AGE = "person_age";    public static final String PERSON_ADDRESS = "person_address";    public static final String PERSON_PHONE = "person_phone";    @DatabaseField(columnName = PERSON_ID, index = true, unique = true, canBeNull = false)    public int id;    @DatabaseField(columnName = PERSON_NAME)    public String name;    @DatabaseField(columnName = PERSON_AGE)    public String age;    @DatabaseField(columnName = PERSON_ADDRESS)    public String address;    @DatabaseField(columnName = PERSON_PHONE)    public String phone;    @Override    public String toString() {        return "id=" + id + "\r name=" + name + "\r age=" + age + "\r address=" + address + "\r phone=" + phone;    }}

The id indicates that it is the primary key. Note: BaseModel must be inherited.

1. Initialization:
public void initDB() {    if (DatabaseManager.getInstance().isInited())        return;    String dbName = "person.db";    int version = 0;    try {        version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;    } catch (NameNotFoundException e) {        e.printStackTrace();    }    List<Class<?>> list = new ArrayList<Class<?>>();    list.add(PersonModel.class);    DatabaseManager.getInstance().initDataBase(getApplicationContext(), dbName, version, list);}

DbName indicates the database name. versionCode is used here for version, so that the database will be upgraded once after each version upgrade. You can also define the list by yourself. The list is the list of ing models to be stored in the database, which must be inherited from the BaseModel. After initialization, the database and table have been created for us.

According to the concept of object relationship ing mode, each table should correspond to a Model. That is to say, if we want to create a person table, we should have a corresponding Person Model class.

2. insert data

One line of code is enough:

DatabaseManager.getInstance().insert(PersonModel.class, model);

If you want to monitor whether insertion fails, you can call the following insert method:

DatabaseManager.getInstance().insert(PersonModel.class, model, new DatabaseManager.getInstance().insert(PersonModel.class, model, new DBOperateAsyncListener() {    @Override    public <T extends BaseModel> void onPostExecute(DatabaseOptionType optionType, Class<T> claz, List<T> successModels, List<T> failModels) {        if (successModels != null) {            Log.i("MrFu", "Success = " + ((PersonModel)(successModels.get(0))).toString());        }else if (failModels != null) {            Log.i("MrFu", "Fail = " + ((PersonModel)(failModels.get(0))).toString());        }    }});

Of course, if my data is in the form of a list, it can also be inserted directly without the need to write a for loop to insert one by one,

DatabaseManager.getInstance().insert(PersonModel.class, models);
3. update Data

It is also a line of code:

DatabaseManager.getInstance().update(PersonModel.class, model1);

He also supports four reload methods. insert is not actually given. Here he provides four reload methods. insert is similar

DatabaseManager.getInstance().update(Class<T> claz, T t);DatabaseManager.getInstance().update(Class<T> claz, List<T> models);DatabaseManager.getInstance().update(Class<T> claz, T t, DBOperateAsyncListener listener);DatabaseManager.getInstance().update(Class<T> claz, List<T> models, DBOperateAsyncListener listener);
4. replace data

This can also be done with one line of code. It also supports four overload methods:

DatabaseManager.getInstance().replace(Class<T> claz, T t);DatabaseManager.getInstance().replace(Class<T> claz, List<T> models);DatabaseManager.getInstance().replace(Class<T> claz, T t, DBOperateAsyncListener listener);DatabaseManager.getInstance().replace(Class<T> claz, List<T> models, DBOperateAsyncListener listener);
5. delete data

The same is true. Where whereClause is the delete condition, and whereArgs is the placeholder of whereClause:

DatabaseManager.getInstance().delete(Class<T> claz, String whereClause, String[] whereArgs);DatabaseManager.getInstance().delete(Class<T> claz, String whereClause, String[] whereArgs, DBOperateDeleteListener listener);

For example, delete data with id 1.

DatabaseManager.getInstance().delete(PersonModel.class, PersonModel.PERSON_ID + " = ?", new String[] {"1"});

This indicates that the data whose person_id is 1 in the PersonModel table is deleted.

6. select data

To query the data of the entire table, you only need to follow the following statement:

DatabaseManager.getInstance().select(PersonModel.class, null, null, null, null, null, null, null);

In fact, this writing is redundant. Therefore, I think I should add the following method:

List<PersonModel> list = DatabaseManager.getInstance().select(PersonModel.class);

In this case, it is much more convenient. If I need to query the data of the entire table, I can directly call this method. Of course, if you want to extend the select method, more select methods can be reloaded for implementation.

The SQLiteDateBase query method is as follows. You can reload the select method based on the corresponding parameters of this method. The parameters are the same:

/*** Query the given table, returning a {@link Cursor} over the result set.** @param table The table name to compile the query against.* @param columns A list of which columns to return. Passing null will*            return all columns, which is discouraged to prevent reading*            data from storage that isn't going to be used.* @param selection A filter declaring which rows to return, formatted as an*            SQL WHERE clause (excluding the WHERE itself). Passing null*            will return all rows for the given table.* @param selectionArgs You may include ?s in selection, which will be*         replaced by the values from selectionArgs, in order that they*         appear in the selection. The values will be bound as Strings.* @param groupBy A filter declaring how to group rows, formatted as an SQL*            GROUP BY clause (excluding the GROUP BY itself). Passing null*            will cause the rows to not be grouped.* @param having A filter declare which row groups to include in the cursor,*            if row grouping is being used, formatted as an SQL HAVING*            clause (excluding the HAVING itself). Passing null will cause*            all row groups to be included, and is required when row*            grouping is not being used.* @param orderBy How to order the rows, formatted as an SQL ORDER BY clause*            (excluding the ORDER BY itself). Passing null will use the*            default sort order, which may be unordered.* @param limit Limits the number of rows returned by the query,*            formatted as LIMIT clause. Passing null denotes no LIMIT clause.* @return A {@link Cursor} object, which is positioned before the first entry. Note that* {@link Cursor}s are not synchronized, see the documentation for more details.* @see Cursor*/public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) {...}

Is it very simple? We don't need to consider how to implement SQLiteOpenHelper or the complicated SQL situations.

This blog mainly describes how to useKopDBFramework, next blog, I will analyze the implementation of this framework to deepen my impression and facilitate future expansion and learning.

This article does not explain SQLite very carefully. For details about SQLite, refer to these two blog posts, which are very detailed:

Guo Lin: Secret of Android database experts

Scott: Explanation of SQLite applications in Android

Related Article

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.