Use of the lightweight database SQLite

Source: Internet
Author: User
Tags gettext sqlite stub

This article does not involve a number of conceptual things, please forgive us a lot




This is the simple frame of Android SQLite.

Using SQLite is about 3 steps

The first step: Create your own Sqliteopenhelper class

Step two: Create a DAO layer in the database with the operations of the database

Step three: Use the DAO layer operation in activity (multi-threaded form, prevent card interface)


First step: Create Sqliteopenhelper

/** * @author Skyfin * @time 2015/6/4 */public class MyDatabase extends Sqliteopenhelper {/** * database name */public final Stati C String db_name = "Classaateinfo";/** * The version number of the database */public final static int version = 1;/** * @param The default constructed function */public Mydat Abase (context context, String name, cursorfactory factory,int version) {Super (context, name, Factory, version);//TODO automatically Into the constructor stub}public MyDatabase (context context, String name, cursorfactory factory,int version, Databaseerrorhandler ErrorHandler) {Super (context, name, Factory, version, ErrorHandler);//todo}/** * @param in order to not pass in the database name and version information each time */public Mydat Abase (Context context) {This (context, db_name, NULL, VERSION);} /** * @param in order to update the database name and version information */public MyDatabase (context context, int version) {This (context, db_name, NULL, version);} /* * (non-Javadoc) * * @see * android.database.sqlite.sqliteopenhelper#oncreate (Android.database.sqlite *). Sqlitedatabase) * Created database primary key ID name and phone */@Overridepublic void OnCreate (Sqlitedatabase db) {//TODO CREATE DATABASE to databaseMake String sql = "CREATE TABLE IF not EXISTS student" + "(" + "ID int primary key autoincrement," + "name varchar ()," + "phone int) ";d b.execsql (SQL);} /* (non-Javadoc) * @see android.database.sqlite.sqliteopenhelper#onupgrade (android.database.sqlite.SQLiteDatabase, int , int) * * Change Database version operation */@Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO Change Database Edition This operation//string sql = "Updete student";//db.execsql (sql);} @Overridepublic void OnOpen (Sqlitedatabase db) {//TODO Open Database Super.onopen (db);}}


Step two: Create Studentdao to encapsulate related operations

public class Studentdao {MyDatabase MyDatabase = Null;public Studentdao (context context) {MyDatabase = new MyDatabase (cont EXT);} Public Studentdao (context context, int version) {myDatabase = new MyDatabase (context, version);} /** * * @param implement data insertion */public void InsertData (Student stu) {/* * method one used (?) The placeholder for the overloaded execsql (String sql, object[] bindargs) method *///try {//LOG.I ("Skyfin", "Insert Datebase" + stu.id);//String sql = "INSERT into student (Id,name,phone) VALUES (?,?,?)";  /Sqlitedatabase db = Mydatabase.getwritabledatabase ();//Db.execsql (SQL, new object[] {stu.id, stu.name, stu.phone});// Db.close ();//} catch (Exception e) {//E.printstacktrace ();///Todo:handle exception//}/* * Method two uses contentvalues word Gencun The form */sqlitedatabase db = Mydatabase.getwritabledatabase (); Contentvalues values = new Contentvalues () values.put ("id", stu.id), Values.put ("name", Stu.name); Values.put ("Phone", Stu.phone); Long rowid = Db.insert ("student", null, values);//Returns the line number of the newly added record, regardless of the primary key ID Db.close ();} Test public void Insert () {log.i ("Skyfin", "Test");} public void Seleteall () {/* * * Method one query form */try {log.i ("Skyfin", "select Datebase"); String sql = "SELECT * from student"; Sqlitedatabase db = Mydatabase.getwritabledatabase (); Produces a new cursor, cursor class forward and backward cursor cursor = db.rawquery (sql,null); while (Cursor.movetonext ()) {int id = cursor.getint (cursor.getcolumnindex ("id")); String name = cursor.getstring (Cursor.getcolumnindex ("name")); int phone = Cursor.getint (Cursor.getcolumnindex ("Phone")); Log print output log.i ("Skyfin", "query-->" + "ID:" +id+ "Name:" +name+ "Phone:" +phone ");} Db.close (); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();} /* * Method two query form *///try {//sqlitedatabase db = Mydatabase.getwritabledatabase ();//cursor Cursor = db.query ("Student" ,//new string[] {"id", "name", "Phone"}, null,//null, NULL, NULL, NULL, NULL);////while (Cursor.movetonext ()) {//log.i ("s Kyfin "," cursor ");//int id = cursor.getint (cursor.getcolumnindex (" id "));//string name = Cursor.getstring (Cursor.getcolumnindex ("name")),//int phone = Cursor.getint (Cursor.getcolumnindex ("Phone")),////log print output//log.i (" Skyfin "," query--> "+" ID: "+ ID +" Name: "+ name//+" Phone: "+ Phone";////}//cursor.close ();//db.close ();/} catch (Exception e) {////TODO auto-generated catch block//e.printstacktrace ();/}} public void Update () {try {sqlitedatabase db = Mydatabase.getwritabledatabase ();//contentvalues is a key-value form, similar to the map Contentvalues values = new Contentvalues () values.put ("id", 1020),//key is the field name, value is Values.put ("name", "Doubi"); Values.put ("Phone", 1234); The//update function is followed by a conditional db.update ("student", Values, "Id=?", New string[]{"123"}); Db.close ();} catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();}} public void Delete () {Sqlitedatabase db = Mydatabase.getwritabledatabase ();//and update similar to Db.delete ("student", "ID<?", New string[]{"$"});d B.close ();}}

Finally used in the activity

public class Mainactivity extends Activity implements Onclicklistener {public Studentdao Studentdao = Null;public EditText edit_id= null;public EditText edit_name= null;public EditText edit_phone= null;public button ok_btn = Null;public button    SHOW_BTN = null;public Button update_btn = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Studentdao = new Studentdao (Getapplicationcontext ());        edit_id = (EditText) Findviewbyid (r.id.id);        Edit_name = (EditText) Findviewbyid (r.id.name);        Edit_phone = (EditText) Findviewbyid (r.id.phonenum);        OK_BTN = (Button) Findviewbyid (R.id.ok);        SHOW_BTN = (Button) Findviewbyid (r.id.show);        UPDATE_BTN = (Button) Findviewbyid (r.id.update);        Ok_btn.setonclicklistener (this);        Show_btn.setonclicklistener (this);    Update_btn.setonclicklistener (this); } @Override Public Boolean OncreateoPtionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @Override public boolean onoptionsitemselected (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 parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); } @Overridepublic void OnClick (View v) {//TODO auto-generated method stub switch (V.getid ()) {Case R.id.ok:toast.maketext (  Getapplicationcontext (), "clicked on the Confirmation button", Toast.length_short). Show (); LOG.I ("Skyfin", "insert into Datebase"), final Student Student = new Student (); Student.setid (Integer.parseint (edit_ Id.gettext (). ToString ()); Student.setname (Edit_name.gettext (). ToString ()); Student.setphone (Integer.parsEint (Edit_phone.gettext (). toString ()));    LOG.I ("Skyfin", student.tostring ()); New Thread (New Runnable () {@Overridepublic void run () {log.i ("Skyfin", "Insert Thread is running"); Studentdao.insertdata (student);}}). Start (); Break;case r.id.show:new Thread (New Runnable () {@Overridepublic void run () {log.i ("Skyfin", "Select Thread is RU Nning "); Studentdao.seleteall ();}). Start (); Break;case r.id.update:new Thread (New Runnable () {@Overridepublic void run () {log.i ("Skyfin", "Update thread is Running "); Studentdao.update ();//studentdao.delete ();}). Start (); break;default:break;}}}


Dome

Use of the lightweight database SQLite

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.