SQLite for Android data storage

Source: Internet
Author: User
Tags sqlite database

SQLite, a lightweight database that adheres to the acid-based relational database management system, is designed to be embedded, and is now used in many embedded products, with very little resources and only hundreds of KB of memory. Support Windows/linux/unix and other mainstream operating systems, and can be combined with other programming languages, such as TCL, C #, PHP, Java, and ODBC interface, the same compared to MySQL, PostgreSQL, the two open source world-renowned database management system, is processing faster than they do. SQLite is currently the most widely used database, based on the above advantages, the Android system using SQLite database.

Sqliteopenhelper Introduction

To manage the database, Android applications provide an abstract class Sqliteopenhelper,sqliteopenhelper class that provides two important methods, namely onCreate () and Onupgrade (), OnCreate is used to generate database tables when the software is first used, and to update the database table structure when Onupgrade is used to upgrade software.

when calling Sqliteopenhelper's Getwritabledatabase () or Getreadabledatabase () method to get the Sqlitedatabase instance used to manipulate the database, if the database does not exist, The Android system automatically generates a database and then calls the OnCreate () method. the onCreate () method is called only when the database is first generated, and in the OnCreate () method, the database table structure can be generated and the initialization data used by some applications to be added.

The Onupgrade () method is called when the version of the database changes, and the version number is usually changed when the software is upgraded, and the version of the database is controlled by the programmer.

assuming that the current version is 1, upgrade the software when you want to update the database table structure of the user's phone, in order to achieve this goal, the original database version can be set to 2, and in the Onupgrade () method to implement the table structure update. When the version of the software upgrade more than the number, then in the Onupgrade () method can be based on the original number and the target version number to judge, and then make the corresponding table structure and data update.

implementation of Demo

First look at a page:

The layout does not have to write, it is four buttons, the purpose is to generate a person database, while generating a table, and then manipulate the data in person:

The first step is to rewrite the methods in the abstract class Sqliteopenhelper

public class Mysqldbhelper extends Sqliteopenhelper {private static final String dbname= "person.db";p rivate staticfinal I NT Version=1;private String tag= "Mysqldbhelper";p ublic mysqldbhelper (context context) {Super (context, DBname, NULL, Version); LOG.I (tag, "Test");} @Overridepublic void OnCreate (Sqlitedatabase db) {//TODO auto-generated method STUBLOG.I (tag, "person created before person in the person database"); String sqlstring= "CREATE TABLE person (ID integer primary key autoincrement,name nvarchar ($), Address nvarchar (200))"; Db.execsql (sqlString); LOG.I (tag, "Person creation success in person database");} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method stublog.i (Tag, "Update the database, do not need to use it for the time being");}}

The database name and version number in the constructor can be fixed, the test does not pass so many parameters, say a bit more about this @override:

@Override is pseudo-code, which means rewriting (and of course not writing), but there are two advantages to writing:
1, can be used as a comment, easy to read;
2, the compiler can give you to verify @override the following method name is all in your parent class, if there is no error. For example, if you do not write @override, and your method name is wrong, then your compiler can be compiled through, because the compiler thought that this method is your child class in the increment of their own method.

Insert data Call here to get Sqlitedatabase, let the post-splicing SQL Direct incoming execution is OK:

public void Insert (view view) {Sqlitedatabase database = Dbhelper.getwritabledatabase (); String sql = "INSERT into person values (NULL,?,?)"; Database.execsql (SQL, new object[] {"Flyelephant", "Beijing"}); LOG.I (Tag, "insert Success");}

Update the data, note here the use of contentvalues, the order of key-value pairs:

public void Update (view view) {Sqlitedatabase database = Dbhelper.getwritabledatabase (); Contentvalues contentvalues = new Contentvalues () contentvalues.put ("Address", "Shenzhen");d atabase.update ("person", Contentvalues, "Name=", new string[] {"Flyelephant"}); LOG.I (tag, "Update succeeded");}

Querying data, where cursors are used, similar to the use of SqlDataReader in C #, MoveToNext can meet basic requirements:

public void query (view view) {Sqlitedatabase database = Dbhelper.getreadabledatabase (); cursor cursor = database.rawquery ("SELECT * from person", null); if (Cursor.getcount () >0) {while (Cursor.movetonext ()) {String namestring = cursor.getstring (Cursor.getcolumnindex ("Name")); String addrestring = cursor.getstring (Cursor.getcolumnindex ("Address")); LOG.I (Tag, "Name:" + namestring + "--address:" + addrestring);}} else {LOG.I (tag, "no Data");} Cursor.close ();}

If you think MoveToNext () can not meet the demand, I looked for someone posted on the Internet code, as follows:

C.move (int offset);//with the current position as a reference, move to the specified line C.movetofirst ();//move to the first line c.movetolast ();//move to the last row c.movetoposition (int position);//move to the specified line c.movetoprevious ();//move to the previous line C.movetonext ();//move to the next line C.isfirst ();//Whether point to the first c.islast ();// Whether to point to the last C.isbeforefirst ();//whether to point to the first bar before C.isafterlast ();//whether to point to the last bar after c.isnull (int columnindex);//Specify whether the column is empty (column cardinality is 0) C.isclosed ();//Whether the cursor is closed c.getcount ();//The total number of data items c.getposition ();//Returns the number of rows pointed to by the current cursor C.getcolumnindex (String columnName);// Returns the column index value corresponding to a column name c.getstring (int columnindex);//Returns the value of the specified column for the current row

Delete data:

public void Delete (View v) {sqlitedatabase database = Dbhelper.getreadabledatabase ();d atabase.delete (' person ', ' name=? ') , new string[] {"Flyelephant"}); LOG.I (tag, "delete succeeded");}

You can look at the results:

The weekend is over again, I hope everyone work tomorrow is fine spirit of God, happy heart, drunk on the weekend ~

SQLite for Android data storage

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.