Android SQLite, kopdb framework Learn to use

Source: Internet
Author: User

Objective

My blog: http://mrfufufu.github.io/
The database is used in recent projects because the amount of data previously required for local storage is not very large and sharedpreferences is sufficient to solve most of the data storage problems, so we have not used SQLite. Now the product needs to optimize the private messaging module experience, so it is necessary to increase the private messaging local storage. It is very necessary to use SQLite at this time. Fortunately, our boss has already encapsulated a very well-established database framework, which can be used. Read the source study of the day, probably have written experience, sorting out, learning to use.

Just give him the name KopDB . (Kop is the tag that our eldest brother used when he played log), KopDB using the object-relational mapping (ORM) pattern, and encapsulating some of the database functions we usually use in our development, so that we can do all kinds of tables without writing a single line of SQL statements, The operation of the inspection and deletion.

This article is mainly about the use of kopdb, specific analysis I will be in the next article.

Github project address, which contains Lib and the corresponding demo, Welcome to Star

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

The main way to use it is simple:

First of all, the data model models in the demo are easy to read and understand later:

 Public  class personmodel extends basemodel {    Private Static Final LongSerialversionuid =3462436436344054489L Public Static FinalString person_id ="person_id"; Public Static FinalString Person_name ="Person_name"; Public Static FinalString Person_age ="Person_age"; Public Static FinalString person_address ="Person_address"; Public Static FinalString Person_phone ="Person_phone";@DatabaseField(ColumnName = person_id, index =true, unique =true, Canbenull =false) Public intId@DatabaseField(ColumnName = person_name) PublicString name;@DatabaseField(ColumnName = person_age) PublicString age;@DatabaseField(ColumnName = person_address) PublicString address;@DatabaseField(ColumnName = person_phone) PublicString phone;@Override     PublicStringtoString() {return "Id="+ ID +"\ r name="+ name +"\ r age="+ Age +"\ r address="+ Address +"\ r phone="+ Phone; }}

Where ID is written to indicate that it is a primary key, note: You must inherit Basemodel.

1. Initialize:
 Public voidInitdb () {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 =NewArraylist<class<?>> (); List.add (Personmodel.class); Databasemanager.getinstance (). Initdatabase (Getapplicationcontext (), DbName,version, list);}

Where DbName is the name of the database, version is used here Versioncode, so that the database will be upgraded once each upgrade version number. Of course you can define it yourself; lists are the list of mapping models that need to be stored in the database and must inherit from Basemodel. Once the initialization is complete, the database and the tables have been created for us.

The idea of mapping patterns according to object relationships is that each table should correspond to a model, that is, if we want to build a person table, there should be a corresponding person model class.

2. Insert Data

One line of code will do:

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

If you want to listen for an insertion failure, you can call the following insert method

Databasemanager.getinstance (). Insert (Personmodel.class, model,NewDatabasemanager.getinstance (). Insert (Personmodel.class, model,NewDboperateasynclistener () {@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 having to write a for loop with one insert,

DatabaseManager.getInstance().insert(PersonModel.class, models);
3. Update data

It's also a line of code:

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

He also supports 4 overloaded methods, the insert is not actually given, here is given his four overloaded methods, insert 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

Also a line of code can be done, also support 4 overloaded 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

Also Oh, where whereclause is the condition of Delete, Whereargs is the placeholder for Whereclause:

DatabaseManager.getInstance().delete(ClassStringString[] whereArgs);DatabaseManager.getInstance().delete(ClassStringString[] whereArgs, DBOperateDeleteListener listener);

As an example, delete the data with ID 1

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

This means that the data in the Personmodel table is deleted from person_id 1.

6. Select data

If you need to query the entire table of data, just follow the following syntax:

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

In fact, it is superfluous to write this. So, I think I should add this method:

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

In this way, it is more convenient, if I need to query the entire table of data, call this method directly, of course, if you want to extend the Select method, you can overload more select method to implement.

The Sqlitedatebase Query method is as follows, you can overload the Select method according to the parameters of this method, the parameters are the same:

/*** Query the givenTablereturningA {@link Cursor} Over  the result Set. * * @param table the tablename  toCompile theQueryagainst. * @param Columns AList  ofwhich columns to return. Passing NULL will*returnAll columns, which isDiscouraged toPrevent reading* Data fromStorage that isn ' tGoing toBe used.* @param selection A filter declaring which rows to return, formatted asan* SQL WHERE clause (excluding theWHERE itself). Passing null* wouldreturnAll rows for  the giventable.* @param selectionargs You may include? sinchSelection, which'll be* replaced by  theValues fromSelectionargs,inchOrder thatthey* appearinch  theSelection. The values would be bound asstrings.* @param groupBy A Filter declaring how toGroup rows, formatted asAn sql* GROUP by clause (excluding theGROUP by itself). Passing null* would cause theRows to  notBe grouped.* @param have A filter declare which row groups toIncludeinch  thecursor,*ifRow grouping isBeing used, formatted asAn SQL having* clause (excluding theHaving itself). Passing NULL would cause* all row groups tobe included, and  isRequired when row* grouping is  notBeing used.* @param toOrder theRows, formatted asAn SQL ORDER by clause* (excluding theORDER by itself). Passing NULL would use the* Default sort order, which may unordered.* @param limit Limits the  Number  ofRows returned by  thequery,* formatted asLIMIT clause. Passing null denotes no LIMIT clause.* @returnA {@link Cursor} object, which isPositionedbefore  the  FirstEntry. Note that* {@link cursor}s is notSynchronized, see theDocumentation forMore details.* @see cursor*/public Cursor Query (string table, string[] columns, string selection, string[] Selectionargs, String groupBy, String having, string by-clause, string limit) {...}

How about, isn't it very simple, we don't need to think about how to implement sqliteopenhelper and don't need to consider the complicated SQL case.

This blog is mainly about how to use the KopDB framework, the next blog, I will be the implementation of the framework of the specific analysis, in order to deepen the impression, to facilitate future expansion and learning.

This article on SQLite is not very detailed explanation, the detailed description of SQLite can refer to these two blog posts, very very detailed:

Guo Lin: Android database Master cheats

Scott:android the application of SQLite in the detailed

Android SQLite, kopdb framework Learn to use

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.