Android xutils Frame (i) dbutils

Source: Internet
Author: User

In Dbutils, only 4 data types are supported:

  1. Public enum Columndbtype {
  2. Integer ("integer"), Real ("real"), text ("text"), Blob ("blob");
  3. private String value;
  4. Columndbtype (String value) {
  5. this.value = value;
  6. }
  7. @Override
  8. Public String toString () {
  9. return value;
  10. }
  11. }

In Java, we have 8 basic types, but when we use dbutils, we can correctly access these data types,
How did this happen?

The first step is to create the database first

Create a database

Daoconfig config = new Daoconfig (context);

Config.setdbname ("Xutils-demo"); Database name

Config.setdbversion (1); Database version number

Dbutils db = dbutils.create (config),//db there are other construction methods, such as the listener containing the version of the Update table, if the listener is not set by default, the old version of the table will be deleted when the upgrade

The second step is to create an entity class based on the requirements, then annotate it, and annotate it as

Here are some common Annotation (annotations)//annotations that are not equivalent to annotations, do not confuse

@Check Check Constraint
@Column column names
@Finder-to-many, many-to-one, many-to-many relationships (see use in the parent, child of sample)
@Foreign FOREIGN Key
@Id primary key, which is the default self-increment when type int. When not self-increment, you need to set the value of the ID
@NoAutoIncrement not self-increasing
@NotNull is not empty
@Table Table Name
@Transient do not write to the database table structure
@Unique UNIQUE Constraint

Inquire

  1. try {
  2. Db.saveall (list);
  3. Db.findall (child.   Class);
  4. Db.findall (Selector.from (child.   Class). WHERE ("id", ">", 2));
  5. Db.findbyid (child.   class, 1);
  6. Db.findfirst (child.   Class);
  7. Db.findfirst (Selector.from (child.   Class). WHERE ("id", ">", 2));
  8. Db.finddbmodelall (Dbmodelselector.from (child.   Class). GroupBy ("hobby"). Having (Wherebuilder.b ("id", ">", 2)));
  9. Db.finddbmodelfirst (Dbmodelselector.from (child.   Class). GroupBy ("hobby"). Having (Wherebuilder.b ("id", ">", 2)));
  10. Cursor C = db.execquery (new Sqlinfo ("select * from Child;"));
  11. //finddbmodelfirst and Finddbmodelall were quite on the ExecQuery did the encapsulation again,
  12. ///Returns a Dbmodel that encapsulates the method of getting value by column name, such as String getString (String columnName), and so on.
  13. Dbmodel model = Db.finddbmodelfirst (new Sqlinfo ("select * from Child;")); //Take native SQL statement, can do long Table query operation
  14. list<dbmodel> modellist = Db.finddbmodelall (new Sqlinfo ("select * from Child;"));
  15. } catch (Dbexception e) {
  16. //TODO auto-generated catch block
  17. E.printstacktrace ();
  18. }

Data for updating the table structure, saving the original data
public static void UpdateTable (Dbutils dbutils, class<?> tclass) {try {if (dbutils.tableisexist (Tclass))            {String tableName = Tclass.getname ();            TableName = Tablename.replace (".", "_");            String sql = "SELECT * from" + tableName;            Fame a MAP is used to save the fields in the original table  map<string, string> filedmap = new hashmap<> ();            Execute a custom SQL statement   CURSOR cursor = dbutils.execquery (SQL);            int count = Cursor.getcolumncount ();            for (int i = 0; i < count; i++) {Filedmap.put (Cursor.getcolumnname (i), cursor.getcolumnname (i));            }//cursor must close  cursor.close () after use.            Some reflection knowledge is used below, which is to get all the private properties of the entity class (that is, all field names after we change the table structure)  field[] fields = UserInfo.class.getDeclaredFields ();                 for (int i = 0; i < fields.length; i++) {if (Filedmap.containskey (Fields[i].getname ())) {   If the field name already exists, make the next loop              continue; } else {//does not exist, it is placed in the map, and a field is added to the table  filedmap.put (Fields[i].getname (), FIELDS[I].GETN                    Ame ());                        Add the field if (Fields[i].gettype (). toString (). Equals ("Class java.lang.String") to the table based on the type of the property {                    Dbutils.execnonquery ("ALTER TABLE" + TableName + "Add" + fields[i].getname () + "TEXT"); } else if (Fields[i].gettype (). Equals ("int") | | fields[i].gettype (). Equals ("Long") | | fields[i].gettype (). Equals (" Boolean ")) {dbutils.execnonquery (" ALTER TABLE "+ TableName +" Add "+ fields[i].getname () +" in                    Teger ");    }}}}} catch (Dbexception e) {e.printstacktrace (); }}




Precautions:
1. When there is an ID or _id in the class, you can omit the annotation for the ID

2. When the id,_id or @id annotation field is an integer, primary key defaults to AutoIncrement
At this point, you can annotate the field with @noautoincrement to make it not self-increment

[Email protected] annotations are for primary key only.

4. In a class, only one @id annotation can be used, primary key is unknown when multiple @id annotations are used

5. In a class, if id,_id is present at the same time, the primary key priority is @Id > ID > _id when @Id

[Email protected] If you use the column parameter, primary key columns are named

[Email protected] If the parameter is not specified, the primary key column is named field name



Dbutils-check Annotations of the Xutils series

Check annotation definition:

    1. @Target (Elementtype.field)
    2. @Retention (Retentionpolicy.runtime)
    3. Public @interface Check {
    4. String value ();
    5. }

Dbutils Parsing code:

    1. String check = Columnutils.getcheck (Column.getcolumnfield ());
    2. if (check! = null) {
    3. Sqlbuffer.append ("Check ("). Append (check). Append (")");
    4. }

Usage:

    1. @Column (column="age")
    2. @Check ("Age >")
    3. private int age;

xutils series dbutils-, delete, update, replace operation

http://blog.csdn.net/androidresearch/article/details/45704337

Android xutils Frame (i) dbutils

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.