Simple application of SQLite database

Source: Internet
Author: User
Tags sqlite sqlite database

SQLite, is a lightweight database, in the Android phone, the SQLite library can parse most of the standard SQL language, the following record simple usage, if there is a person passing by found errors, please help me to point out, so that I correct. Here is a simple example, mainly for the convenience of learning from their own memory.

1. First build a tool class DBHelper inherit the Sqliteopenhelper class. Defines the DBHelper constructor and the overloaded OnCreate () and Onupdgrade () methods.

OnCreate (): Used to create database usage;

Onupdgrade (): Used to update the database;

1  Public classDBHelperextendsSqliteopenhelper {2 3     //constructor, parameter super (context, database name, cursor factory, database version)4      PublicDBHelper (Context context) {5         Super(Context, Constant.db_name,NULL, constant.version);6     }7 8 @Override9      Public voidonCreate (Sqlitedatabase db) {TenDb.execsql ("CREATE table IF not EXISTS '" "+constant.user_table+" ' " One+ "(_id INTEGER PRIMARY KEY autoincrement, name TEXT, img text)"); A     } -  - @Override the      Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { -  -     } -}

2. Build a constant class (not mandatory, optional) Constant, used to store some related constants, such as database name, version number, etc.:

1  Public classConstant {2      Public Static FinalString db_name = "uu.db";//Database name3      Public Static Final intVERSION = 1;//Database Version4      Public Static FinalString user_table = "USER";//User Data table name5}

3. Implement a mapping of the data table, that is, the bean class (if I remember correctly), to construct the user object.

1  Public classUser {2     PrivateLong ID;3     PrivateString name;4     PrivateString img;5 6      PublicLong getId () {7         returnID;8     }9 Ten      Public voidsetId (Long id) { One          This. ID =ID; A     } -  -      PublicString GetName () { the         returnname; -     } -  -      Public voidsetName (String name) { +          This. Name =name; -     } +  A      PublicString getimg () { at         returnimg; -     } -  -      Public voidsetimg (String img) { -          This. IMG =img; -     } in  - @Override to      PublicString toString () { +         return"User{" + -"id=" + ID + the", Name= ' + name + ' + ' + *", img= ' + img + ' + ' + $‘}‘;Panax Notoginseng     } -}

4. Set up the DAO class, that is, the user table (users) to complete the increase, delete, change, check operation of the amount of method, the other classes in the need to call the method directly.

/*** Created by Administrator on 2015/8/1. * For the implementation of adding or deleting the operation*/ Public classUserdao {PrivateDBHelper DBHelper =NULL; PrivateSqlitedatabase db =NULL; PrivateContentvalues values =NULL;  PublicUserdao (Context context) {DBHelper=NewDBHelper (context); }    /*** Add a user *@paramUser *@return     */     Public LongaddUser (user user) {//get sqlitedatabase for database operation, open write operationdb =dbhelper.getwritabledatabase (); //parameter Binding objectValues =Newcontentvalues (); Values.put ("Name", User.getname ()); Values.put ("IMG", User.getimg ()); //store operation, the ID returned here is not the actual ID, but the line number where the record is located and is correct if it has never been deleted        Longid = Db.insert (constant.user_table,NULL, values); //Freeing ResourcesDbhelper.close (); returnID;//String sql = "INSERT into user (NAME,IMG) VALUES ('" +name+ "', '" +img+ "')";//Sqlitedatabase db = Dbhelper.getwritabledatabase ();//db.execsql (SQL);    }    /*** Delete a user by ID *@paramID *@return     */     Public voidDeleteUser (String ID) {db=dbhelper.getwritabledatabase (); Db.delete (constant.user_table,"_id=" +id,NULL);    Db.close (); }    /*** Update an object *@paramUser *@return     */     Public intupdateUser (user user) {db=dbhelper.getwritabledatabase (); Contentvalues Values=Newcontentvalues (); Values.put ("Name", User.getname ()); Values.put ("IMG", User.getimg ()); intk= db.update (constant.user_table,values, "_id=" +user.getid (),NULL);        Db.close (); returnK; }    /*** Query user information by ID *@paramuesr_id *@return     */     PublicUser Finduserbyuserid (String uesr_id) {return NULL; }    /*** Get all Users *@return     */     PublicList<user>findallusers () {db=dbhelper.getreadabledatabase (); String SQL= "Select _id,name,img from" + Constant.user_table + "ORDER by _id Desc"; Cursor Cursor= Db.rawquery (SQL,NULL); List<User> list =NewArraylist<user>(); //Use the following effect is better, but first to determine whether there is data. Then the array opens up a certain space, determined by the Cursor.getcount ()//list<user> List = new arraylist<user> (Cursor.getcount ());         while(Cursor.movetonext ()) {User User=NewUser (); User.setid (Cursor.getlong (0)); User.setname (Cursor.getstring (1)); User.setimg (Cursor.getstring (2));        List.add (user); } cursor.close ();//Close CursorsDb.close (); returnlist; }}

Simple application of SQLite database

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.