Basic operational guidelines for embedded SQLite databases in Android applications _android

Source: Internet
Author: User
Tags sqlite throw exception

First, write a class to inherit Sqliteopenhelper class

Rewrite his method to specify the name, version of DB, rewrite the Oncreat and Onupgrade methods, write SQL statements to create a table

public class Mysqliteopenhelper extends Sqliteopenhelper {
  private static String name = "Person.db";
  private static int version = 1;
  Public Mysqliteopenhelper {
    super (context,name,null,version);  
  }
   * * * The method that the database was invoked the first time it was created
   *db is the database created
  /@Override public
  void OnCreate (Sqlitedatabase db) {
    db.execsql ("CREATE TABLE person (ID integer PRIMARY key autoincrement,name varchar (), number varchar ())";
  /* Call this method when the database version is updated
  /* @Override public
void Onupgrade (sqlitedatabase db, int oldversion, int newversion ) {

  }

Second, create a DAO class to provide external additions and deletions to check the interface
in which the implementation of additions and deletions of the method can be used in SQL statements can also use the system given the API, the following code in the two methods are written out

public class Persondao {private Mysqliteopenhelper helper;
  Public Persondao () {} public Persondao (context context) {helper = new Mysqliteopenhelper (context);
    public void Add (String name,string number) {Sqlitedatabase db = Helper.getwritabledatabase ();
    Db.execsql ("INSERT into person (name,number) VALUES (?,?)", New Object[]{name,number});
    /*contentvalues values = new Contentvalues ();
    Values.put ("number", number);
    Values.put ("name", name);

  Long id = db.insert ("person", null, values); */Db.close ();
    public boolean find (String name) {Sqlitedatabase db = Helper.getwritabledatabase ();
    Cursor Cursor = Db.rawquery ("Select *from person where Name=?", New String[]{name});
    Cursor Cursor = db.query ("person", NULL, "Name=?", new string[]{name},null,null, NULL);
    Boolean result =cursor.movetonext ();
    Cursor.close ();
    Db.close ();    
  return result; public int update (String name,string newnumber) {Sqlitedatabase db =Helper.getwritabledatabase (); Db.execsql ("Update person set number=?")
    Where Name=? ", New Object[]{newnumber,name});
    Contentvalues values = new Contentvalues ();
    Values.put ("number", Newnumber);
    int number = Db.update ("Person", Values, "Name=", New String[]{newnumber});
    Db.close ();
  return number;
    public int delet (String name) {Sqlitedatabase db = Helper.getwritabledatabase ();
    Db.execsql ("Delete from person where name=?", New String[]{name});
    int number = Db.delete ("Person", "Name=?", New String[]{name});  
    Db.close ();

  return number;
    Public list<person> FindAll () {list<person> persons = new arraylist<person> ();
    Sqlitedatabase db = Helper.getwritabledatabase ();
    Cursor Cursor = Db.rawquery ("Select *from person", NULL);
    Cursor Cursor = db.query ("Person", new string[]{"id", "name", "number"}, NULL, NULL, NULL, NULL, NULL); while (Cursor.movetonext ()) {int id = cursor.getint (cursor.getcolumnindex ("id"));
      String name = cursor.getstring (Cursor.getcolumnindex ("name"));
      String number = cursor.getstring (Cursor.getcolumnindex ("number"));
      Person p = new person ();

    Persons.add (P);
    } db.close ();
    Cursor.close (); 

  return persons;

 }

}

Third, add a check operation

Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
 
Import Android.database.sqlite.SQLiteOpenHelper;
  public class Tododb extends Sqliteopenhelper {private final static String database_name = "todo_db";
  Private final static int database_version = 1;
  Private final static String table_name = "todo_table";
  Public final static String field_id = "_id";
 
  Public final static String Field_text = "Todo_text";
  Public Tododb {Super (context, database_name, NULL, database_version); @Override public void OnCreate (Sqlitedatabase db) {/* CREATE TABLE/String sql = "CREATE TABLE" + Table_nam
    E + "(" + field_id + "INTEGER primary key AutoIncrement," + "" + Field_text + "TEXT)";
  Db.execsql (SQL); @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {String sql = DROP TABLE IF EXISTS "+table_name;
    Db.execsql (SQL);
  OnCreate (DB);
    Public Cursor Select () {Sqlitedatabase db = This.getreadabledatabase ();
    Cursor Cursor = db. query (table_name, NULL, NULL, NULL, NULL, NULL, NULL);
  return cursor;
    Public long Insert (String text) {Sqlitedatabase db = This.getwritabledatabase ();
    /* Add new value into Contentvalues/contentvalues CV = new Contentvalues ();
    Cv.put (Field_text, TEXT);
    Long row = Db.insert (table_name, NULL, CV);
  return row;
    The public void delete (int id) {Sqlitedatabase db = This.getwritabledatabase ();
    String where = field_id + "=?";
    String[] Wherevalue = {integer.tostring (id)};
  Db.delete (table_name, where, wherevalue);
    public void update (int id, String text) {Sqlitedatabase db = This.getwritabledatabase ();
    String where = field_id + "=?";
    String[] Wherevalue = {integer.tostring (id)};
   /* Add the modified value to Contentvalues/contentvalues CV = new Contentvalues (); Cv.put (Field_text, TEXT);
  Db.update (TABLE_NAME, CV, where, wherevalue);
 }
}

Iv. Write a JavaBean setting his get, set method

public class Person { 
  private int id;
  private String name;
  private String number;

  Public person () {

  } public person

  (int id, string name, string number) {
    this.id = ID;
    this.name = name;
    This.number = number;
  }
  public int getId () {return
    ID;
  }
  public void setId (int id) {
    this.id = ID;
  }
  Public String GetName () {return
    name;
  }
  public void SetName (String name) {
    this.name = name;
  }
  Public String GetNumber () {return number
    ;
  }
  public void Setnumber (String number) {
    this.number = number;
  }

}

V. Use it in mainactivity

Private Sqliteopenhelper helper;
Persondao dao = new Persondao ();

Helper = new Mysqliteopenhelper (this);
Helper.getwritabledatabase ();    
Sqlitedatabase db = Helper.getwritabledatabase ();

VI. Transaction processing of databases
the operation of the database in Android development is very slow, and packing all the operations into a single transaction can greatly improve the processing speed, in which the most important thing is to ensure the consistency of the data, so that all operations in the transaction can be executed successfully or failed, or all of these operations are rolled back.

Sqlitedatabase db = Helper.getwritabledatabase ();
Db.begintransaction ();
try{

 //performs multiple database operations here and may throw exception db.execsql during execution
 ("Update person set number=?"). Where Name=? ", New object[]{" 1 ", Jacky});
 Db.execsql ("Update person set number=?") Where Name=? ", New object[]{" 2 "," Sunny "});
 Db.settransactionsuccessful ();
} catch{
 //catch exception
 throw e;
}finally{//
  All operations complete a transaction
  db.endtransaction ();
  Db.close;
}

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.