SQLite database additions and Deletions check operation

Source: Internet
Author: User
Tags sqlite sqlite database stub

1, Sqliteopenhelper for the database abstract class, you need to create a class to inherit him, there are oncreate to create the database abstract methods and Onupgrade upgrade database methods (generally not used).

1 //to create a database class2 //Sqliteopenhelper abstract class OnCreate and Onupgrade abstract methods3  Public classMysqlitehelperextendsSqliteopenhelper {4     5     //New database and table6     PrivateString sqlcpdata= "CREATE TABLE Tablecpdata (ID integer primary key autoincrement,"7+ "Cp_num varchar", time varchar (20));;8     9     Ten      PublicMysqlitehelper (Context context) { One          This(Context, "tablecpdata.db",NULL, 1); A     } -      -      PublicMysqlitehelper (context context, String name, Cursorfactory factory,intversion) { the         Super(context, name, Factory, version); -         //TODO auto-generated Constructor stub -     } -      +     //Create a Database abstraction method - @Override +      Public voidonCreate (Sqlitedatabase db) { A         //TODO auto-generated Method Stub atDb.execsql (Sqlcpdata);//perform a new database operation -LOG.I (sqlcpdata, "Database creation succeeded"); -     } -      -     //Upgrade Database - @Override in      Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { -         //TODO auto-generated Method Stub to          +     } -      the      *}

2. Then create a method class that defines how to get the operation and the time

//define how to get operations and time Public classRule { Public intID;  PublicString Cp_num;  PublicString time; //Get ID     Public intGetID () {returnID; }    //Set ID     Public voidSetId (intID) { This. id=ID; }         PublicString Getcpnum () {returnCp_num; }         Public voidsetcpnum (String cp_num) { This. cp_num=Cp_num; }         PublicString GetTime () {returnTime ; }         Public voidsettime (String time) { This. time=Time ; }        //the method of the class     PublicRule (intID, String cp_num, String time) {        Super();  This. ID =ID;  This. Cp_num =Cp_num;  This. Time =Time ; }     PublicRule () {Super(); }    }

3, and then create a database of a delete and modify class

//database additions and deletions check and change operation Public classCpdatadao {PrivateMysqlitehelper Mysqlitehelper;//defining database Operation functions         PublicCpdatadao (Context context) {Mysqlitehelper=NewMysqlitehelper (context);//instantiating database operation functions    }        //Insert Database     Public LongInsert (String cp_num,string time) {//instantiating a Sqlitedatabase objectSqlitedatabase database=mysqlitehelper.getwritabledatabase (); Contentvalues contentvalues=Newcontentvalues (); Contentvalues.put ("Cp_num", Cp_num); Contentvalues.put ("Time", time); returnDatabase.insert ("Tablecpdata",NULL, contentvalues); //indicates, default value for empty column, insert encapsulated column name, and column value    }    PrivateRule rule=NULL; //A collection of stored data    PrivateList<rule> dataList =NULL; /*** Check ALL data * *@returnData Collection*/         PublicList<rule>Queryall () {Sqlitedatabase db=mysqlitehelper.getreadabledatabase (); Cursor Cursor= Db.query ("Tablecpdata",                NewString[] {"id", "cp_num", "Time"},NULL,NULL,NULL,NULL,                NULL); if(Cursor! =NULL&& cursor.getcount () > 0) {dataList=NewArraylist<rule>();  while(Cursor.movetonext ()) {rule=NewRule (); Rule.setid (Cursor.getint (0)); Rule.setcpnum (Cursor.getstring (1)); Rule.settime (Cursor.getstring (2));            Datalist.add (rule); }        }        returndataList; }        /*** Delete all data *@return0 Delete succeeded, 1 delete failed*/     Public intDeleteAll () {Try{sqlitedatabase db=mysqlitehelper.getwritabledatabase (); //return Db.delete ("student", NULL, NULL);String sql = "Delete from Tablecpdata";            Db.execsql (SQL); return0; } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        return1; }        }

There are also operations that are conditionally queried, and note that modifying the database name and indicating that it is consistent with the above

    /*** Enquiry Time * *@returnData Collection*/    //querying the collection of data//list<rule> timelist=null;     PublicList<rule> Querytimerecord (FinalString time) {Sqlitedatabase db=dsopenhelper.getreadabledatabase (); String SqlUser= "SELECT * from Ruledata where time is like?"; String [] Sqlselect=Newstring[] {"%" + Time + "%",        }; Cursor Cursor=db.rawquery (SqlUser, sqlselect); if(Cursor! =NULL&& cursor.getcount () > 0) {        //Userpassward = new arraylist<user> ();             while(Cursor.movetonext ()) {rule Rule=NewRule (); Rule.setid (Cursor.getint (0)); Rule.setoperation (Cursor.getstring (1)); Rule.settime (Cursor.getstring (2)); //userpassward.add (user);datalist.add (rule); }        }        returndataList; }

4, finally in their own class of these methods to invoke operation, you can realize the change of SQLite and delete operation

For example, the data received by the lower computer to insert data

(1) Declare the class in the class global variable first

Private Cpdatadao cpdatadao=new Cpdatadao (this); Database additions and deletions search and change class

(2) Then call the method of the class to insert the data

Cpdatadao.insert (Device.getname (), Time ()); Insert the name of a device and the current system time

(3) (2) The current system time method is obtained from

    // Get system time function    Private String Time () {        new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");         New Date (System.currenttimemillis ()); // get current time        String str_time = Formatter.format (curdate);         return str_time;    }

5, the operation of querying data is similar, through the class to invoke the method, here is the query to the data displayed in a TextView interface

(1) statement

Private Cpdatadao cpdatadao=new Cpdatadao (this);
Private Cpdatadao deledatadao=new Cpdatadao (this);

Private LinearLayout llcontent;
Private TextView TV;

(2) query all the methods

    //Check all charge records    Private voidQueryall () {//mlistview.removeallviews ();llcontent.removeallviews (); List<Rule> datalist=Cpdatadao.queryall (); if(datalist!=NULL) {             for(Rule rule:datalist) {TV=NewTextView ( This); //mlistview=new ListView (mcontext); //List.add (New Devicelistitem ("Charging pile:" +rule.getcpnum () + "Time:" +rule.gettime (), true));Tv.settext ("\ T" +rule.getid () + "." + "Charging pile:" +rule.getcpnum () + "+" Time: "+rule.gettime () +" \ n ");                Tv.settextcolor (Color.Blue); Tv.settextsize (16);                Llcontent.addview (TV); LOG.I ("Database Data", "" "+rule.getcpnum () +rule.gettime ()); } log.i ("Database Query", "Query Database Success"); }    }

(3) Delete all

Btndelected.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method Stubllcontent.removeallviews (); //Deledatadao.deleteall ();                intLine=Deledatadao.deleteall (); if(line==0) {log.i ("All data deleted successfully", "" "+Line ); Toast.maketext (Mcontext,"All data successfully deleted", Toast.length_short). Show (); } Else{toast.maketext (Mcontext,"No data currently", Toast.length_short). Show (); }                            }        });

SQLite database additions and Deletions check operation

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.