Introduction to the use of the Android SQLite

Source: Internet
Author: User
Tags sqlite database

Introduction to the use of SQLite for AndroidSQLitethe introduction

The built-in sqlite database in Android, what is the characteristic of SQLite ?

SQLite is an open-source, embedded relational database that implements a self-contained, 0 configuration, transactional SQL database engine. It is characterized by its high portability, ease of use, compact structure, high efficiency and reliability. Unlike other database management systems,SQLite is very simple to install and run, in most cases - just make sure that sqlite Binary file exists to start creating, connecting, and using the database. in the personal experience of using SQLite ,the biggest advantage ofSQLite is highly portable, in some small stand-alone applications to do data storage is very advantageous. After summarizing The characteristics of SQLite have the following aspects:

1.Lightweight

With SQLite you only need to bring a dynamic library, you can enjoy its full functionality, and the size of the dynamic library want to be small.

2.Independence

the core engine of the SQLite database does not need to rely on third-party software, nor does it require the so-called "install".

3.Isolation of

all information in the SQLite database (such as tables, views, triggers, etc.) is contained within a folder for easy administration and maintenance.

4.Cross-platform

SQLite currently supports most of the operating systems, not the computer operating system more in the many mobile phone systems can also be run, such as:Android.

5.Multi-lingual interface

The SQLite database supports multiple language programming interfaces.

6.Security

the SQLite database implements independent transaction processing through exclusive and shared locks at the database level. This means that multiple processes can read data from the same database at the same time, but only one can write data.

TwoAndroidin theSQLiteRelated Classes1,Sqlitedatabase

Sqlitedatabase represents a database that can be manipulated by adding, deleting, modifying, querying, and other related SQL commands, while also supporting a common subset of SQL instructions. the Sqlitedatabase class provides us with many methods, and the more common methods are as follows :

A convenient way to delete data rows

(int) Delete (String table,string whereclause,string[] whereargs)

A convenient way to add data rows

(long) Insert (String table,string nullcolumnhack,contentvalues values)

A convenient way to update data rows

(int) Update (string table, contentvalues values, String whereclause, string[] whereargs)

Executes an SQL statement that can be a select or other SQL statement

(void) execsql (String sql)

Close the database

(void) Close ()

Queries the specified data table to return a data set with a cursor

(Cursor) query (string table, string[] columns, string selection, string[] Selectionargs, String groupBy, string having, St Ring, String limit)

Run a pre-built SQL statement that returns a data set with a cursor (the biggest difference from the above statement is that it prevents SQL injection)

(Cursor) rawquery (String sql, string[] selectionargs)

2,Sqliteopenhelper

Sqliteopenhelper is a helper class for sqlitedatabase that manages the creation of databases and the updating of versions. It is generally established that a class inherits it and implements its onCreate and Onupgrade methods.

Constructs a method, typically passing a database name to be created so the parameter

Sqliteopenhelper (Context context,string name,sqlitedatabase.cursorfactory factory,int version)

Called when a database is created

OnCreate (Sqlitedatabase db)

Called when the version is updated

Onupgrade (sqlitedatabase db,int oldversion, int newversion)

Create or open a read-only database

Getreadabledatabase ()

Create or open a read-write database

Getwritabledatabase ()

Third, AndroidinSQLitethe related Operations1. Opening of Sqliteopenhelper and creation of Sqlitedatabase

When creating Sqliteopenhelper, the constructor needs to provide basic information, such as context, database name, version number, and so on.

/** static helper class for creating, updating, and opening databases */  private static class Dbopenhelper extends Sqliteopenhelper {public   Dbopenhelper (context context, String name, Cursorfactory factory, int version) {    Super (context, name, Factory, version);  }   private static final String db_create = "CREATE table" +     db_table + "(" + key_id + "Integer primary KEY autoincreme NT, "+    key_name+" text NOT NULL, "+ key_volume+" integer, "+ key_weight +" float);   @Override public  void OnCreate (Sqlitedatabase _db) {    _db.execsql (db_create);  }   @Override public  void Onupgrade (sqlitedatabase _db, int _oldversion, int _newversion) {        _db.execsql ("DROP TABLE IF EXISTS "+ db_table);    OnCreate (_db);  }}


  /** Open the database *  /public void Open () throws sqliteexception {    dbopenhelper = new Dbopenhelper (context, Db_n AME, NULL, db_version);  try {  db = Dbopenhelper.getwritabledatabase ();  }  catch (Sqliteexception ex) {  db = Dbopenhelper.getreadabledatabase ();  }  }


2, the Sqliteopenhelper closed

/** Close the database */public  void Close () {  if (db! = null) {  db.close ();  db = null;}  }

3. Adding data to the database

/** * * * * * * *   /public  long Insert (Storage Storage) {    contentvalues newValues = new Contentvalues ();      Newvalues.put (Key_name, storage. Name);    Newvalues.put (Key_volume, storage. Volume);    Newvalues.put (key_weight, storage. Weight);        Return Db.insert (db_table, NULL, newValues);  }


4. Data in the query data

Through the code, we can see

(Cursor) query (string table, string[] columns, string selection, string[] Selectionargs, String groupBy, string having, St Ring, String limit)

The GroupBy parameter of this method is also a conditional statement


/**   * Query all data   * *  /public storage[] Queryalldata () {    Cursor results =  db.query (db_table, New string[ ] {key_id, key_name, Key_volume, key_weight}, NULL, NULL, NULL, NULL, NULL   );  return Converttostorage (results);     }


  /**   * Query Single Data   * *  /public storage[] Queryonedata (long id) {    Cursor results =  db.query (db_table, New string[] {key_id, key_name, Key_volume, key_weight},   key_id + "=" + ID, NULL, NULL, NULL, NULL);  return Converttostorage (results);     }

5. Delete database data

/**   * Clear All data   * *  /public long Deletealldata () {  return db.delete (db_table, NULL, NULL);  }

/**   * Clear Single Data   * *  /public long deleteonedata (long id) {  return Db.delete (db_table,  key_id + "=" + ID, n ull);  }

6. Data Update

/**   * Update single Data   * *  /public long updateonedata (long ID, Storage people) {  contentvalues updatevalues = new Co Ntentvalues ();    Updatevalues.put (Key_name, people. Name);  Updatevalues.put (Key_volume, people. Volume);  Updatevalues.put (Key_weight, people. Weight);    Return Db.update (db_table, updatevalues,  key_id + "=" + ID, NULL);  }

Demo: http://download.csdn.net/detail/stop_pig/7884569

Introduction to the use of the Android SQLite

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.