A package class teaches you to learn SQLite database

Source: Internet
Author: User
Tags sqlite sqlite database

the name of the database operation class usually ends with DAO, what is DAO?

DAO (data Access Object) is the first object-oriented database interface

Data entity class
 Public classTree {Private intIdPrivateString name;Private intAgePrivate floatPrice Public int getId() {returnId } Public void setId(intID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } Public float GetPrice() {returnPrice } Public void Setprice(floatPrice) { This. Price = Price; } Public Tree() {    } Public Tree(String name,intAgefloatPrice) { This. name = name; This. Age = Age; This. Price = Price; } @Override PublicStringtoString() {return "tree{"+"Id="+ ID +", Name= '"+ name +' \ '+", age="+ Age +", price="+ Price +'} '; }}
Database Operations Encapsulation Class
 Public  class Treedbdao {    Private Static FinalString db_name ="Tree.db";//Database name    Private Static FinalString table_name ="Treeinfo";//Data table name    Private Static Final intDb_version =1;//Database version    //The field name of the table    Private StaticString key_id ="id";Private StaticString Key_name ="Name";Private StaticString Key_age ="Age";Private StaticString Key_price ="Price";PrivateSqlitedatabase mdatabase;PrivateContext Mcontext;PrivateTreedbopenhelper Mdbopenhelper;//Database Open Help class     Public Treedbdao(Context context)    {Mcontext = context; }//Open Database     Public void OpenDatabase() {Mdbopenhelper =NewTreedbopenhelper (Mcontext, Db_name,NULL, db_version);Try{mdatabase = Mdbopenhelper.getwritabledatabase ();//Get writable database}Catch(SQLException e) {mdatabase = Mdbopenhelper.getreadabledatabase ();//Get read-only database}    }//Close Database     Public void CloseDataBase() {if(Mdatabase! =NULL) {mdatabase.close (); }    }//Insert a piece of data     Public Long InsertData(Tree tree) {Contentvalues values =NewContentvalues ();        Values.put (Key_name, Tree.getname ());        Values.put (Key_age, Tree.getage ()); Values.put (Key_price, Tree.getprice ());returnMdatabase.insert (TABLE_NAME,NULL, values); }//Delete a piece of data     Public Long DeleteData(LongID) {returnMdatabase.delete (table_name, key_id +"="+ ID,NULL); }//Delete all data     Public Long Deletealldata() {returnMdatabase.delete (TABLE_NAME,NULL,NULL); }//Update one piece of data     Public Long UpdateData(LongID, tree) {Contentvalues values =NewContentvalues ();        Values.put (Key_name, Tree.getname ());        Values.put (Key_age, Tree.getage ()); Values.put (Key_price, Tree.getprice ());returnMdatabase.update (table_name, values, KEY_ID +"="+ ID,NULL); }//Query One piece of data     PublicList<tree>Querydata(LongID) {Cursor results = mdatabase.query (table_name,Newstring[]{key_id, Key_name, Key_age, Key_price}, key_id +"="+ ID,NULL,NULL,NULL,NULL);returnConverttotree (results); }//Query all data     PublicList<tree>querydatalist() {Cursor results = mdatabase.query (table_name,Newstring[]{key_id, Key_name, Key_age, Key_price},NULL,NULL,NULL,NULL,NULL);returnConverttotree (results); }PrivateList<tree>Converttotree(Cursor cursor) {intResultcounts = Cursor.getcount ();if(Resultcounts = =0|| !cursor.movetofirst ()) {return NULL; } list<tree> mtreelist =NewArraylist<> (); for(inti =0; i < resultcounts; i++) {Tree tree =NewTree (); Tree.setid (Cursor.getint (0));            Tree.setname (Cursor.getstring (Cursor.getcolumnindex (Key_name)));            Tree.setage (Cursor.getint (Cursor.getcolumnindex (key_age)));            Tree.setprice (Cursor.getfloat (Cursor.getcolumnindex (Key_price)));            Mtreelist.add (tree);        Cursor.movetonext (); }returnMtreelist; }/** * Data Sheet Open Help class */    Private Static  class treedbopenhelper extends sqliteopenhelper {         Public Treedbopenhelper(context context, String name, Sqlitedatabase.cursorfactory factory,intVersion) {Super(context, name, Factory, version); }@Override         Public void onCreate(Sqlitedatabase db) {FinalString sqlstr ="CREATE table if not exists"+ table_name +" ("+ key_id +"Integer primary key AutoIncrement,"+ Key_name +"text NOT NULL,"+ Key_age +"Integer,"+ Key_price +"float);";        Db.execsql (SQLSTR); }@Override         Public void Onupgrade(Sqlitedatabase DB,intOldversion,intNewVersion) {FinalString sqlstr ="DROP TABLE IF EXISTS"+ table_name;            Db.execsql (SQLSTR);        OnCreate (DB); }    }}
How to use
Treedbdao Mdbdao= NewTreedbdao (mainactivity.this);//instanced objectsMdbdao.OpenDatabase ();//Open Database//Delete and change the operationMdbdao.InsertData (NewTree ("GreenTree", A,2321.5f));//Add DataMdbdao.DeleteData (1);//Delete dataMdbdao.UpdateData (1,NewTree ("RedTree", -,5200f));//Update dataMdbdao.Deletealldata ();//Delete all dataList<Tree> List =Mdbdao.Querydata (1);//query for data with ID 1Log.V" --",List.Get0).ToString ());List<Tree>Lists=Mdbdao.Querydatalist ();//Query all datafor (Tree tree:lists) {Log.V" --", tree.ToString ());}
Store Results

A package class teaches you to learn 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.