C # Programmer learns SQLite for Android development series

Source: Internet
Author: User

The previous blog mentioned SQLite, which is an embedded database, because of its lightweight but powerful, is widely used in embedded devices. Later, after the popularity of smartphones and tablets, as a file-based database, it almost became a must-have for the smart Device standalone database, which can be packaged into the APK file with the Android app.

The official website of SQLite is http://www.sqlite.org/, can be downloaded arbitrarily, the above also has the detailed document to refer to, this blog focuses on how SQLite is used in Android development.

In Android development, it is recommended to establish a class that inherits from Sqliteopenhelper to create database operation classes, such as:

public class DBHelper extends Sqliteopenhelper {private static final String database = "Test.db";p rivate static final Inte GER Version = 1;public DBHelper (context context) {//constructor initializes each member variable super (context, database, NULL, version);} @Overridepublic void OnCreate (Sqlitedatabase db) {//When a database connection is obtained from a subclass of Sqliteopenhelper, if the database does not exist, Call the OnCreate method to create the database string sql = "CREATE TABLE score (ID integer primary key autoincrement,name varchar (), point Integer)" ;d b.execsql (SQL);} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//when the database version number of the incoming instance is higher than the previous version number, The system automatically calls the Onupgrade method to update the database//update the database: Back up the database table data, recreate or modify tables, constraints, and so on, and then import the original data into the newly created table. }}
The above code has 3 points to note:

1. The name and version number of the database are specified in the constructor (method)

It will default in the data/data/package name/databases/directory to create this database, of course, you can also specify the path of the database file exists, the version number is set to 1, if you want to upgrade, you can add version to the parameters of the constructor method in order to initialize.


2, OnCreate is executed when the database file is not created, if any, do not execute

3, Onupgrade is in the new specified version number is higher than the old specified version number of time to execute, generally in the database upgrade needs to operate

Then we build a specific database operation class:

/** * Score Operation class * * @author Guwei * */public class Scoreop {//Insert a transcript public long insert (Sqlitedatabase db, String name, in Teger point) {try {db.begintransaction (); Contentvalues values = new Contentvalues (), Values.put ("name", name), Values.put ("point", point), long result = Db.insert ( "Score", null, Values), if (Result! =-1) {db.settransactionsuccessful ();} return result;} finally {db.endtransaction ();}} Modify a transcript public int update (Sqlitedatabase db, String name, Integer point) {try {db.begintransaction (); Contentvalues values = new Contentvalues (), Values.put ("name", name), Values.put ("point", point), int result = Db.update (" Score ", values," name =? ", new string[] {name});d b.settransactionsuccessful (); return result;} finally {db.endtransaction ();}}  Delete a transcript public long delete (Sqlitedatabase db, String name) {try {db.begintransaction (); int result = Db.delete ("Score", "name =?", new string[] {name});d b.settransactionsuccessful (); return result;} finally {db.endtransaction ();}} Queries are queued according to the nameThe first 10 points of the order are greater than the specified number of personnel information public Cursor query (sqlitedatabase db, Integer point) {return db.query ("Score", new string[] {"Name", "Sum" as points "}, NULL, NULL," name "," sum (point) >= "+ Point," name ASC "," 0,10 ");} More flexible queries, SQL arbitrary splicing public Cursor query (sqlitedatabase db, String sql, string[] selectionargs) {return db.rawquery (SQL, Sele Ctionargs);}}
This encapsulates the CRUD operations, all with transactions (required to execute multiple SQL), and the last two query methods are worth paying attention to.

The first query is a case where a complex SQL query statement is specified.

In order, the parameters have the following meanings:

1),table the table name to compile the query against.

The table name of the specified query

2),columns A list of which columns to return. Passing NULL would return all columns, which are discouraged to prevent reading data from storage This isn ' t going to being use D.

Column name of the returned query list

3),selection A filter declaring which rows to return, formatted as a SQL WHERE clause (excluding the Where Itsel f). Passing null would return all rows for the given table.

Where condition, not including where keyword

4),Selectionargs You may include? s in selection, which'll be replaced by the values from Selectionargs, in Ord Er that they appear in the selection. The values would be bound as Strings.

The parameter value specified by the Where condition

5),groupBy A Filter declaring how to group rows, formatted as a SQL GROUP BY clause (excluding the group by Itse LF). Passing null would cause the rows to is grouped.

Column names followed by the group by group

6), have A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as An SQL has clause (excluding the having itself). Passing null would cause all row groups to be included, and was required when row grouping was not being used.
Having to be followed in the next section on a group basis

7), order the rows, formatted as a SQL ORDER BY clause (excluding the order by itself). Passing NULL would use the default sort order, which could be unordered.

Order BY is followed by a field

8),limit Limits The number of rows returned by the query, formatted as limit clause. Passing null denotes no LIMIT clause.
The Limit keyword, used when paging queries

In fact, the corresponding 8 parameters, which corresponds to the following SQL query statement after the keyword of the content, the principle is to use the specified parameters to join the following SQL statement.

Here by the way, SQLite expert is a very useful tool to manage the SQLite database, can be downloaded to the http://www.sqliteexpert.com/, or directly search to download the corresponding cracked version.

Back to the second query method, the arguments are simple, with only one SQL statement and a string array (providing the value of the SQL statement parameter). The significance of this method is that it is flexible, can be executed directly into the SQL execution, and is parameterized, is the first query method is a strong complement.

Well, finally we can write the test code to verify. The interface is simple to answer, just place a button.

public class Sqliteactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_sqlite); Button btn = (button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {dbhelper dbhelper = new DBHelper (sqliteactivity.this);//Get a writable Database operation object Sqlitedatabase wdb = Dbhelper.getwritabledatabase ();//Add record Scoreop Scoreop = new Scoreop (); Scoreop.insert (wdb, "Zhang3", 98); Scoreop.insert (wdb, "Zhang3", 94), Scoreop.insert (wdb, "Li4", and Scoreop.insert (wdb, "Wang5", Scoreop.insert); , "Wang5", 82);//Modify Record Scoreop.update (wdb, "Li4", 90);//delete record Scoreop.delete (wdb, "li4");//Get a readable database operation object Sqlitedatabase RDB = Dbhelper.getreadabledatabase ();//1. You can call the system-supplied query method to return the cursor object in the form of a specified parameter//cursor cursor = Scoreop.query (RDB, 192 );//2. You can execute SQL query statements directly cursor cursor = Scoreop.query (RDB, "select Name,sum (point) as points from score group by name have Su M (point) >=192 orDer by name ASC Limit?,? ", new string[] {" 0 "," Ten "}), while (Cursor.movetonext ()) {String name = cursor.getstring (cursor). Getcolumnindex ("name")); Integer points = Cursor.getint (Cursor.getcolumnindex ("points")); Toast.maketext (Sqliteactivity.this, "name:" + name + "; Score:" + points, Toast.length_short). Show (); Cursor.close ();}});}}
After clicking on the button, you can eject the qualifying data. If you are not at ease, you can switch to the DDMS interface, select the File Explorer tab, locate the Test.db file we created under the path, and open the validation with tools such as SQLite expert.




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.