Android using Ormlite (i): Table creation and deletion and change check

Source: Internet
Author: User
Tags sql quote sqlite create database
Ormlite is a lightweight ORM framework that is oriented to the Java language. It is also one of the most popular Android ORM frameworks. Using SQLite data in Android is probably a good choice if you don't want to write Sql,ormlite.

Use Ormlite, first in Gradle configuration dependent compile ' com.j256.ormlite:ormlite-android:4.48 ' can also go to ormlite website Download View document http://ormlite.com/
1. Table creation
Then you want to create an entity class that corresponds to the table structure. Ormlite provides two annotations, @DatabaseField represent table column names, @DatabaseTable table names tablename values are the real names of the tables in the database. The following user class must have a parameterless constructor.
You need to specify a field as a unique flag, an int, an Integer, long, long, and a record in the UUID type database to be uniquely identified by defining a unique special field. Record is not required to have a unique identity field many DAO operations (update, delete, refresh) require a unique identification field at that time. This identity is either provided by the user or automatically generated by the database. Identity fields have unique values in the table and they must exist if you use DAO to query, delete, refresh, or update specified rows based on IDs.  In order to configure a member variable as an identity member, you should use one of the following three settings (and must use one): @DatabaseField: ID, Generatedid, generatedidsequence. @DatabaseField (id = true) specifies which field the primary key @DatabaseField (Generatedid = true) automatically increases the ID @DatabaseField (Generatedidsequence = True Sets the sequence name to match the existing schema, you can use Generatedidsequence to specify the value of the sequence name.
So you can use the ID to do delete, modify, query and other operations. Otherwise, the associated method is called to throw the cannot query-for-id with class Xxx.xxx.xxx.User because it doesn ' t have an ID field-related exception.
@DatabaseTable (tablename = "T_user") public
class User {

    @DatabaseField (generatedid =true)
    private int id;

    @DatabaseField
    private String name;

    public User (int ID, String name) {
        this.name = name;
        This.id = ID;
    }

    Public User () {
    } public

    String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    public int getId () {return
        ID;
    }

    public void setId (int id) {
        this.id = ID;
    }
}


Android uses SQLite need to inherit from Sqliteopenhelper, to use ormlite need to inherit ormlitesqliteopenhelper, to implement some create database, create tables, Update table operations. Tableutils is a tool class that mainly provides the creation of tables, the removal of tables, and so on.
public class DBHelper extends Ormlitesqliteopenhelper {private dbhelper (contexts context) {//parameter: Contextual, database name, CU
        Rsor Factory, database version.
    Super (context, "test.db", NULL, 1); ///The first time the database is invoked, the @Override public void OnCreate (Sqlitedatabase sqlitedatabase, connectionsource connections
        Ource) {try {tableutils.createtable (Connectionsource, User.class);
        catch (SQLException e) {e.printstacktrace (); }///When the database version is upgraded, it is called @Override public void Onupgrade (Sqlitedatabase sqlitedatabase, Connectionsource con Nectionsource, int i, int i1) {try {//) Here's just a rough way to remove the old table and create a new table, which will result in data loss, which is generally not true tableutils.dr
            Optable (Connectionsource, User.class, true);
        OnCreate (Sqlitedatabase, Connectionsource);
        catch (SQLException e) {Orm e.printstacktrace ();
   
    }//Implement a singleton return DBHelper instance private static DBHelper helper; public static DbhelpeR Gethelper {if (helper = null) {helper = new DBHelper (context);
    } return helper; }
}

2. Check and delete of the table first, we get an instance of Ormlitesqliteopenhelper through the singleton class above, and there is a Getdao (class<t> clazz) method in the class that can get the DAO object of the corresponding entity. Parameter Clazz is the class object for the corresponding entity of the table, such as User.class.
By Getdao return a dao<t, id> example, the DAO has the method of increasing the pruning check.
Get an instance of DAO from helper
Private Dao<user, integer> Userdao;

Public Userdao () {
    init ();
}

private void Init () {
    DBHelper dbhelper = Dbhelper.gethelper (Contextprovider.getapplicationcontext ());
    try {
        Userdao = Dbhelper.getdao (User.class);
    } catch (SQLException e) {
        e.printstacktrace ();
    }
}

Add a record to the table public int create (T data) throws SQLException;
Add a record to the table, and if the table does not exist, determine whether there is a public T createifnotexists (t data) throws SQLException based on the primary key set;
Add a record to the table, and if it exists, update a record for the primary key, public createorupdatestatus createorupdate (T data) throws SQLException;
User user = new user ();
Userdao.create (user);
Userdao.createorupdate (user);
Userdao.createifnotexists (user);


Delete
Deletes the public int delete (T data) throws SQLException based on the incoming entity;
Deletes the public int Deletebyid (ID id) throws SQLException by ID;
Deletes the public int delete (collection<t> datas) throws SQLException according to the collection;
Deletes the public int deleteids (collection<id> IDs) throws SQLException according to the collection of IDs;
Userdao.deleteids (IDs);
Userdao.deletebyid (ID);
Userdao.delete (user);
Userdao.delete (list);

Update
Update data based on incoming entity, ID is unique flag public int update (T data) throws SQLException;
Update ID, other values unchanged public int UpdateID (T data, ID newId) throws SQLException;
Mdao.update (New User (1, "Update"));
Updates the data Mdao.updateid for the specified row of IDs

(new User (MId, Mname), 10000);
Update the current row ID to 10000

Inquire
Retrieves a record based on a unique flag ID, if the ID is public T queryforid (ID id) throws SQLException;
The first public T Queryforfirst (preparedquery<t> preparedquery) throws SQLException in all rows to which the query matches;
Returns all entries in the table that can cause a large amount of data to be imported into memory and should use the iterator method instead of this method public list<t> Queryforall () throws SQLException;
query specifies the row for which the field value equals the query value: where FieldName = value public list<t> queryforeq (String fieldName, Object value) throws Sqlexce ption;
Matches the value of each field in an incoming entity (a field cannot be the default, null,false,0,0.0, etc.), with each condition and operation, the result of which can result in SQL quote escaping public list<t> Queryformatching (T matchobj) throws SQLException;
With the above method, the SQL quote escaping public list<t> Queryformatchingargs (T matchobj) throws SQLException is not caused;
Query public list<t> queryforfieldvalues (map<string, object> Fieldvalues) based on the Map match of the passed-in field and value value throws SQLException;
Query public list<t> Queryforfieldvaluesargs (map<string, object> Fieldvalues) based on the Map match of the passed-in field and value value throws SQLException;
Query the data row public T Queryforsameid (t data) throws SQLException that is equal to the incoming entity ID;
Mdao.queryforall ();
Mdao.queryforid (MID);



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.