Android SQLite Simple Use example

Source: Internet
Author: User

About SQLite

Google for Andriod's larger data processing provides SQLite, he is in the storage, management, maintenance and other aspects of the excellent, the function is very strong.

The pocket-sized SQLite supports databases up to 2TB in size, each of which exists as a single file stored on disk in the form of a B-TREE data structure.
In terms of transactional processing, SQLite implements independent transactions with exclusive and shared locks at the database level. This means that multiple processes can read data from the same database at the same time, but only one can write data. An exclusive lock must be obtained before a process or thread wants the database to perform a write operation. After an exclusive lock is obtained, other read or write operations will no longer occur.
SQLite takes a Dynamic data type, and when a value is inserted into the database, SQLite checks its type, and if the type does not match the associated column, SQLite attempts to convert the value to the type of the column, and if it cannot, the value is stored as its own type, which SQLite calls " Weak type ". However, there is a special case, if the integer PRIMARY KEY, then the other type will not be converted, will be reported a "datatype Missmatch" error.
In summary, SQLite supports NULL, Integer, REAL, text, and BLOB data types, representing null values, integer values, floating-point values, string literals, and binary objects, respectively.

SQLite also includes the following features:

1. SQLite3 supports NULL, INTEGER, REAL (floating point number), text (string literal), and blob (binary object) data types, although it supports only five types, but actually sqlite3 also accepts varchar (n), char (n) , Decimal (P,s) and other data types, except that they are converted to the corresponding five data types when they are calculated or saved.
2, the biggest feature of SQLite is that you can save any type of data into any field, regardless of the data type declared by this column. For example, you can hold a string in an integer field, or hold a floating-point number in a Boolean field, or hold a date-type value in a character field.
3. There is one exception: a field defined as an integer PRIMARY key can store only 64-bit integers, and when data other than integers is saved to such a field, an error is generated.
4. In addition, SQLite ignores the data type information that follows the field name in the CREATE TABLE statement when parsing the CREATE TABLE statement, as the following statement ignores the type information for the Name field:
CREATE TABLE person (PersonID Integer primary key autoincrement, name varchar (20))

Personsqliteopenhelper class

public class Personsqliteopenhelper extends Sqliteopenhelper {    /**     * Database Construction method     * Result set of database query, NULL to use default result set     * Database version, starting from 1, less than 1 throws exception     * @param context *    /Public Personsqliteopenhelper (context context) {        Super (context, "person.db", NULL, 1);    }    /**     * Database is called when it is first created, table structure, initialization     * Data type length is useless, just for programmers to see     * @param sqlitedatabase database */    @ Override public    void OnCreate (Sqlitedatabase sqlitedatabase) {        sqlitedatabase.execsql ("CREATE TABLE person (ID integer primary key autoincrement, name varchar (), number varchar) ");    @Override public    void Onupgrade (sqlitedatabase sqlitedatabase, int i, int i1) {    }}

Persondao class

public class Persondao {private Personsqliteopenhelper helper;    Public Persondao (Context context) {helper = new Personsqliteopenhelper (context);        } public void Add (string name, string number) {Sqlitedatabase db = Helper.getwritabledatabase ();        Db.execsql ("INSERT into person (name,number) VALUES (?,?)", New Object[]{name,number});    Db.close ();        } public boolean find (String name) {Sqlitedatabase db = Helper.getwritabledatabase ();        cursor cursor = db.rawquery ("select * from person where name=?", New String[]{name});        Boolean result = Cursor.movetonext ();        Cursor.close ();        Db.close ();    return result;        public void Update (string name, String newnumber) {Sqlitedatabase db = Helper.getwritabledatabase (); Db.execsql ("Update person set number=?")        Where Name=? ", New Object[]{newnumber, name});    Db.close (); } public void Delete (String name) {Sqlitedatabase db = Helper.getwritabledaTabase ();        Db.execsql ("Delete from person where name=?", New String[]{name});    Db.close ();        } public list<person> FindAll () {Sqlitedatabase db = Helper.getreadabledatabase ();        list<person> persons = new arraylist<person> ();        cursor cursor = db.rawquery ("Select Name,id,number from", null);            while (Cursor.movetonext ()) {int id = cursor.getint (cursor.getcolumnindex ("id"));            String name = cursor.getstring (Cursor.getcolumnindex ("name"));            String number = cursor.getstring (Cursor.getcolumnindex ("number"));            Person p = new person (id,name,number);        Persons.add (P);        } cursor.close ();        Db.close ();    return persons; }}

Person class

public class Person {    private int id;    private String name;    private String number;    Public person () {    } public person    (int id, string name, string number) {        this.id = ID;        this.name = name;        This.number = number;    }    public int getId () {        return ID;    }    public void setId (int id) {        this.id = ID;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public String GetNumber () {        return number;    }    public void Setnumber (String number) {        this.number = number;    }    @Override public    String toString () {        return "person{" +                "id=" + ID +                ", name= ' + name + ' + ' +                " , number= ' + number + ' \ ' + '                } ';}    

Applicationtest class

public class Applicationtest extends applicationtestcase<application> {public applicationtest () {Super (A    Pplication.class); } public void Testdbhelp () throws exception{personsqliteopenhelper persql = new Personsqliteopenhelper (getconte        XT ());    Persql.getwritabledatabase ();        } public void Testadd () throws exception{Persondao dao = new Persondao (GetContext ());    Dao.add ("Xiaoming", "18500003039");        } public void Testfind () {Persondao dao = new Persondao (GetContext ());        Boolean result = Dao.find ("Xiaoming");    Assertequals (true, result);        } public void Testupdate () {Persondao dao = new Persondao (GetContext ());    Dao.add ("The Handsome", "13100001423");        } public void Testdelete () {Persondao dao = new Persondao (GetContext ());    Dao.delete ("Xiao Ming");        } public void Testfindall () {Persondao dao = new Persondao (GetContext ());        list<person> persons = Dao.findall (); for (person P:pErsons) {System.out.println (p.tostring ()); }    }}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android SQLite Simple Use example

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.