Android xUtils3.0 User Manual (ii)-Database operations

Source: Internet
Author: User

Steps:

(1). Create a data table;

(2). Daoconfig Obtain the configuration information of the database;

(3). Get DB instance: X.getdb (Daoconfig);

(4). Database additions and deletions to check.

1. Create a data table

It is emphasized here that the time of the creation of the table in the database, only when you are involved in the operation of the database in the operation of the table, will first determine whether the current table exists, if not exist, will create a table, if present, will be the corresponding CRUD operations.

1 @Table(name = "Person") 2  Public classPerson {3     @Column(name = "ID", Isid =true, Autogen =true)4      Public intID;5     @Column(name = "Name")6      PublicString name;//name7     @Column(name = "Age")8      Public intAge//Age9     @Column(name = "SEX")Ten      PublicString sex;//Sex11
A @Override
- public String toString () { - return "person [id=" + ID + ", name=" + name + ", age=" + age + ", sex=" + sex + "]"; the }
+ }

The above table contains the DB-related annotations:

1  @Check Check constraint2  @Column column names3 @Finder-to-many   , many-to-one, many-to-many relationships (see use in the parent, child of sample)4  @Foreign foreign key5  @Id primary Key, which is the default self-increment when type int. When not self-increment, you need to set the value of the ID6  @NoAutoIncrement not self-increasing7  @NotNull is not empty8  @Table table name9  @Transient do not write to the database table structureTen @UniqueUnique constraint

Annotation Properties

name (String)       :  table name    isid (boolean)      :  Whether the primary key Autogen (Boolean )   :  false) proprety (String)   :  

2. Daoconfig get configuration information for the database
1 //initialization of local data2Dbmanager.daoconfig Daoconfig =NewDbmanager.daoconfig ()3. Setdbname ("My_db.db")//Set database name4. setdbversion (1)//sets the database version, which will be checked each time the app is launched.5         //discovering that the database version is lower than the value set here will upgrade the database and trigger Dbupgradelistener6. Setallowtransaction (true)//set whether transactions are turned on, default to False to close transactions7. Settablecreatelistener (NewDbmanager.tablecreatelistener () {8 @Override9                  Public voidOntablecreated (DbManager DbManager, tableentity<?>tableentity) {Ten                 } One         }) A. Setdbopenlistener (NewDbmanager.dbopenlistener () { - @Override -                  Public voidondbopened (DbManager db) { the                     //turn on Wal, boost write acceleration - db.getdatabase (). enablewriteaheadlogging (); -                 } -         }) +         //set the listener when the database is created -. Setdbupgradelistener (NewDbmanager.dbupgradelistener () { + @Override A                  Public voidOnupgrade (DbManager db,intOldversion,intnewversion) { at                     //TODO: ... -                     //db.addcolumn (...); -                     //db.droptable (...); -                     // ... -                     //or -                     //db.dropdb (); in                 } -});//set the listener of the database upgrade, where you can perform related modifications to the related database tables, such as ALTER statements to add fields, etc. to         //. Setdbdir (null);//sets the directory where the database. db file is stored, default to the databases directory under the name of the package +              -DBManager db = X.getdb (daoconfig);

3. Get a DB instance
DbManager db = X.getdb (daoconfig);

4. Table Operations

By Dbmanager This type of action we can do the following:

. getdaoconfig  //  Gets the configuration information for the database . Getdatabase   //  gets  the DB instance . Replace       // only available if there is a unique index (discreet). droptable     //. AddColumn     //. dropdb        //  Delete database

5. Add operation
1 Try {2list<person> list =NewArraylist<person>();3     // ... Loading Data4 5Db.save (list);//Save list to database for entity class or entity class6Db.saveorupdate (list);//saves or updates the list of entity classes or entity classes to the database, depending on the ID of the data exists7Db.savebindingid (list);//saves the list of entity classes or entity classes to the database, and if the ID of the type is automatically generated, the ID will be assigned after saving8}Catch(dbexception e) {9}

6. Delete operation
1 Try {2Db.delete (person.class);//the method is to delete all the data in the table3Db.deletebyid (person.class, 12);//This method is mainly based on the table's primary key (ID) for a single record deletion4Db.delete (person.class, Wherebuilder.b ("Age", ">", "20"));//Delete operation based on the conditions of the WHERE statement5list<person> findAll = db.selector (person.class). Expr ("Age > 20"). FindAll ();6Db.delete (FINDALL);//Delete one or more data from a table based on the entity Bean7}Catch(dbexception e) {8}

7. Change operation
1 //First Kind2 Try {3list<person> findAll = Db.findall (person.class);4      for(person Person:findall) {5Person.setage (10);6     }7Db.update (FindAll, "age");//You can make objects, collections8}Catch(dbexception e) {9 }Ten //The second Kind One Try { Apersontable person = Db.findbyid (person.class, 1); -Person.setage (25); -Db.update (person, ' age '); the}Catch(dbexception e) { -}

8. Check operation
1 Try {2Db.findbyid (person.class, 1);//data from the lookup table by the value of the primary key3Db.findfirst (person.class);//returns the first piece of data in the current table4list<person> findAll = Db.findall (person.class);//returns all data in the current table5Db.finddbmodelall (NewSqlinfo ("SELECT * from person where age >"));6Dbmodel model = Db.finddbmodelfirst (NewSqlinfo ("SELECT * from person where age >"));7Model.getstring ("Age");//model is equivalent to a cursor8list<person> findAll2 = db.selector (person.class). Expr ("Age >10"). FindAll ();//is primarily used to search for certain conditions.9}Catch(dbexception e) {Ten}

9. Related Information

? Android xUtils3.0 User Manual (i)-Basic function Usage

Android xUtils3.0 User Manual (ii)-Database operations

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.