SQLite is a lightweight database that is commonly used in a variety of embedded devices.
Android provides an abstract class for Sqliteopenhelper to help develop a database.
In practice, a class is often defined to inherit sqliteopenhelper, and the method of constructing methods, OnCreate () methods and OnUpdate () are overridden;
Note: The above three methods must be overridden: the overriding constructor method is typically used to initialize a
OnCreate () Method:
OnUpdate () is called when the database version is updated and is called only once when the database is updated.
such as: Mysqlitehelper class inherits Sqliteopenhelper
Mysqliteopenhelper extends Sqliteopenhelper;
Mysqliteopenhelper Myhelper;
Myhelper = new Mysqliteopenhelper (contenext);
* * sqlitedatabase is an object that directly operates the database, you can use the Sqliteopenhelper getreadabledatabase
Or Getwritabledatabase method to get the Sqlitedatabase object.
Sqlitedatabase db = Myhelper.getreadabledatabase ();
Note: only the getreadabledatabase () or Getwritabledatabase method is called to actually create the database, then you can use the various methods of the database,
Processing of data;
return value of query result: cursor cursor; The cursor corresponds to the result set resulytset;
The cursor is a cursor interface that provides methods for traversing query results, such as Move pointer method Move (), Get column value Method GetString (), and so on.
Summary: General steps for using SQLite:
A: Customize a class that inherits Sqliteopenhelper, and then use the object of the database helper class to call the Getreadabledatabase () or Getwritabledatabase method to create the database
B: The operation of the database DB for additional pruning and checking
C: The result set for the query is stored in the cursor.
D: Database DB and result set cursor is used to call the Close method to free resources
Http://wenku.baidu.com/view/423a00dca58da0116c17491e.html
This document is relatively long and detailed
Packagecom.itheima.db;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.database.sqlite.SQLiteDatabase.CursorFactory;ImportAndroid.database.sqlite.SQLiteOpenHelper;ImportAndroid.view.View; Public classPersonsqliteopenhelperextendsSqliteopenhelper {/*a database is constructed to define the name of the database, the result set of the database, and the version of the database to create a person's database*/ PublicPersonsqliteopenhelper (Context context) {Super(Context, "person.db",NULL, 1); /** Total four parameters, meaning of each parameter: 1.context context, generally requires 2: database name cursor Factory: Moving pointer to result set, general cursor factory NULL; Version: Represents the edition of the database. Starting from 1, the general use of 1;*/ } /** Use OnCreate () when the database is first created, * generally used to create the table structure of the database and to save some initialized table parameters * Incoming parameter db represents the database being created **/@Override Public voidonCreate (Sqlitedatabase db) {//Initialize table structureDb.execsql ("CREATE TABLE person" (ID integer primary key autoincrement,name varchar (), number varchar (20)) "); //Note: SQLite is actually an embedded database that does not have as many data types as MySQL. } @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { //TODO auto-generated Method Stub }}
The code above creates a class that inherits the Sqliteopenhelper.
PackageCom.itheima.db.dao;Importjava.util.ArrayList;Importjava.util.List;ImportAndroid.content.Context;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportCom.itheima.db.PersonSQLiteOpenHelper;ImportCom.itheima.db.domain.Person; Public classPersondao {//because you want to manipulate the helper, the class needs to have a helper object PrivatePersonsqliteopenhelper Helper; PublicPersondao (Context context) {Helper=NewPersonsqliteopenhelper (context); } //the constructor of any function is passed to the context object because the context is equivalent to the global variable for the entire application's interface//The benefit of writing this code is that Personhelper has been initialized in the construction method//Habit : Just get the database and write the Close method in the back. Public voidInsert (string name, String num) {Sqlitedatabase db=helper.getwritabledatabase (); Db.execsql (Insert into person (name,number) vlaues (?,?),Newobject[]{name, num}); Db.close (); } //database DB, which is created only after the helper invokes the Getwritabledatabase () or Getreadabledatabase () method//use any database to close the database to release resources, so when you start to create a database, you shut down the database directly in case you forget//database db can call Execsql's method to execute SQL statements, in SQL statements? Represents a placeholder that can be implemented with parameters Public voidDelete (String name) {Sqlitedatabase db=helper.getwritabledatabase (); Db.execsql ("Delete from person where name =?",Newobject[]{name}); Db.close (); } Public voidUpdate (string name, string newname) {Sqlitedatabase db=helper.getwritabledatabase (); Db.execsql ("Update person set name =?" WHERE name =? ",Newobject[]{name,newname}); Db.close (); } Public BooleanFind (String name) {Sqlitedatabase db=helper.getreadabledatabase (); Cursor Cursor= Db.rawquery ("select * from person where name =?",Newstring[]{name}); Booleanresult =Cursor.movetonext (); Cursor.close (); Db.close (); returnresult; } //The cursor is also closed to release resources when it is finished. The cursor is a common method to master PublicList<person>FindAll () {Sqlitedatabase db=helper.getreadabledatabase (); Cursor Cursor= Db.rawquery ("SELECT * FROM person",NULL); List<Person> list =NewArraylist<person>(); while(Cursor.movetonext ()) {intid = cursor.getint (0); String name= cursor.getstring (1); String Number= Cursor.getstring (2); Person P=NewPerson (Name,number,id); List.add (P); } cursor.close (); Db.close (); returnlist; }}//The above is the use of SQL statements are implementation of additions and deletions to search//You can use the API provided by Android to implement additions and deletions.//using SQL statements is cumbersome and there are some small details of errors
Write a DAO class to manipulate the database.
PackageCom.itheima.db.domain; Public classPerson {PrivateString name; PrivateString number; Private intID; PublicPerson (string name, string number,intID) {Super(); This. Name =name; This. Number =Number ; This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString GetNumber () {returnNumber ; } Public voidSetnumber (String number) { This. Number =Number ; } Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } }//Create a Personbean class to encapsulate the results of the query, shortcut right-click Source, generate getter and setter methods, right-click source can also generate a constructor method//the function of the general construction method is to initialize the value of the object parameter
Customizes a person class to encapsulate query results.
Packagecom.itheima.db;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem; Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); Personsqliteopenhelper Helper=NewPersonsqliteopenhelper ( This); /*//Execute the above code only the actual database is not created, the simple new comes out an object helper.getreadabledatabase (); Helper.getwritabledatabase (); Only one of the two methods above has been executed to create the database.*/helper.getreadabledatabase (); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//Handle Action Bar item clicks here. The Action Bar would//automatically handle clicks on the Home/up button, so long//As you specify a the parent activity in Androidmanifest.xml. intID =Item.getitemid (); if(id = =r.id.action_settings) { return true; } return Super. onoptionsitemselected (item); }}
Main function
Android's SQLite summary