Learning notes for Android using SQLite

Source: Internet
Author: User

<1> SQLite Introduction
SQLite is a very popular embedded database. It supports the SQL language and has good performance only with a small amount of memory. In addition, it is open-source and can be used by anyone. Many open-source projects (Mozilla, PHP, Python) Use SQLite.
SQLite consists of the following components: SQL Compiler, kernel, backend, and attachment. SQLite makes debugging, modification, and expansion of SQLite kernel more convenient by using virtual machines and virtual database engine (VDBE ).
SQLite basically conforms to SQL-92 standards, and other major SQL database is no difference. Its advantage is its efficiency. The Android runtime environment contains the complete SQLite.
The biggest difference between SQLite and other databases is its support for data types. When creating a TABLE, you can specify the Data Type of a column in the create table statement, however, you can put any data type into any column. When a value is inserted into the database, SQLite checks its type. If this type does not match the associated column, SQLite will try to convert the value to the column type. If the conversion fails, the value is stored as its own type. For example, you can put a String in the INTEGER column. SQLite calls this "weak type" (manifest typing .).
In addition, SQLite does not support some standard SQL functions, especially the FOREIGN KEY constraints (FOREIGN KEY constrains), nested transcaction and RIGHT OUTER JOIN and FULL OUTER JOIN, and some ALTER TABLE functions.
In addition to the above functions, SQLite is a complete SQL System with complete triggers and transactions.
<2> Android integrates the SQLite Database
Android integrates SQLite at runtime, so every Android application can use the SQLite database. For developers familiar with SQL, using SQLite in Android development is quite simple. However, JDBC consumes too much system resources, so JDBC is not suitable for memory-constrained devices such as mobile phones. Therefore, Android provides some new APIs to use the SQLite database. In Android development, programmers need to learn to use these Apis.
The database is stored in data/<project folder>/databases.
<3> using SQLite database in Android Development
Activites can access a database through Content Provider or Service. The following describes in detail how to create a database, add data, and query a database.
<4> Create a database
Android does not automatically provide databases. To use SQLite in Android applications, you must create your own database, create tables, indexes, and fill in data.
* Android provides SQLiteOpenHelper to help you create a database. As long as you inherit the SQLiteOpenHelper class, you can easily create a database. The SQLiteOpenHelper class encapsulates the logic used to create and update databases based on the needs of application development. SQLiteOpenHelper subclasses must implement at least three methods:
The constructor that calls the constructor of the parent class SQLiteOpenHelper. This method requires four parameters: context (for example, an Activity), Database Name, and an optional cursor Factory (usually Null ), an integer that represents the database model version you are using.
OnCreate () method, which requires a SQLiteDatabase object as the parameter, fill in the table and initialization data for this object as needed.
OnUpgrage () method, which requires three parameters: A SQLiteDatabase object, an old version number and a new version number, in this way, you can understand how to transform a database from an old model to a new model.
[Java]
Package mars. sqlite3.db;
 
Import android. content. Context;
Import android. database. sqlite. SQLiteDatabase;
Import android. database. sqlite. SQLiteOpenHelper;
Import android. database. sqlite. SQLiteDatabase. CursorFactory;
 
// DatabaseHelper serves as an Assistant class for accessing SQLite and provides two functions,
// First, getReadableDatabase (), getWritableDatabase () can obtain the SQLiteDatabse object, through which you can operate on the database
// Second, The onCreate () and onUpgrade () callback functions are provided, allowing us to perform our own operations when creating and upgrading databases.
 
Public class DatabaseHelper extends SQLiteOpenHelper {

Private static final int VERSION = 1;
[Java]
// This constructor must exist in the subclass of SQLiteOepnHelper.
Public DatabaseHelper (Context context, String name, CursorFactory factory,
Int version ){
// The constructor in the parent class must be called through super
Super (context, name, factory, version );
// TODO Auto-generated constructor stub
}
Public DatabaseHelper (Context context, String name ){
This (context, name, VERSION );
}
Public DatabaseHelper (Context context, String name, int version ){
This (context, name, null, version );
}
 
// This function is executed when the database is created for the first time. In fact, this method is called only when the SQLiteDatabse object is obtained for the first time.
@ Override
Public void onCreate (SQLiteDatabase db ){
// TODO Auto-generated method stub
System. out. println ("create a Database ");
// ExecSQL function is used to execute SQL statements
Db.exe cSQL ("create table user (id int, name varchar (20 ))");
}
 
@ Override
Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){
// TODO Auto-generated method stub
System. out. println ("update a Database ");
}
 
}
 
Next we will discuss how to create tables, insert data, and delete tables.
Call the getReadableDatabase () or getWriteableDatabase () method to obtain the SQLiteDatabase instance. The method to call depends on whether you need to change the database content.
<5> Create tables and Indexes
To create tables and indexes, you must call the execSQL () method of SQLiteDatabase to execute DDL statements. If no exception exists, this method does not return a value.
[Java]
Db.exe cSQL ("create table user (id int, name varchar (20 ))");
<6> Insert)
One way is to use the insert () of the SQLiteDatabase object (). These methods take part of the SQL statement as a parameter. Example:
[Java]
// Generate the ContentValues object
ContentValues values = new ContentValues ();
// To insert a key-value pair to the object, the key-value pair is the column name and the value is the value to be inserted into the column. The value must be consistent with the data type in the database.
Values. put ("id", 1 );
Values. put ("name", "zhangsan ");
DatabaseHelper dbHelper = new DatabaseHelper (SQLiteActivity. this, "test_mars_db", 2 );
SQLiteDatabase db = dbHelper. getWritableDatabase ();
// Call the insert method to insert data to the database.
Db. insert ("user", null, values );
<7> update Data)
Use update () of the SQLiteDatabase object (). These methods take part of the SQL statement as a parameter. Example:
[Java]
// Get a writable SQLiteDatabase object
DatabaseHelper dbHelper = new DatabaseHelper (SQLiteActivity. this, "test_mars_db ");
SQLiteDatabase db = dbHelper. getWritableDatabase ();
ContentValues values = new ContentValues ();
Values. put ("name", "zhangsanfeng ");
// The first parameter is the name of the table to be updated.
// The second parameter is a ContentValeus object.
// The third parameter is the where clause.
Db. update ("user", values, "id =? ", New String [] {" 1 "});
Similar to DDL in SQL
Update user set name = 'zhangsanfeng' where id = 1
<8> query)
Use the query () and cursor of the SQLiteDatabase object.
Cursor:
No matter how you perform the query, a Cursor is returned. This is the SQLite database Cursor of Android. You can use the Cursor:
Use the getCount () method to obtain the number of records in the result set;
Use the moveToFirst (), moveToNext (), and isAfterLast () Methods to traverse all records;
Get the field name through getColumnNames;
Use getColumnIndex () to convert it into a field number;
Use getString (), getInt (), and other methods to obtain the value of the current record of the given field;
Query the cursor through requery () method;
Use the close () method to release cursor resources;
These methods take part of the SQL statement as a parameter. Example:
[Java]
Public Cursor query (String table, String [] columns, String selection, String [] selectionArgs,
String groupBy, String having, String orderBy, String limit)
The first parameter table is the name of the data table.
 
String [] columns, and this parameter corresponds to the "column name" in the SQL statement"
The String followed by where is the String selection parameter corresponding to the Android method. In Android method, there is usually a parameter related to this: String [] selectionArgs. When the selection parameter contains a question mark "? ", Then selectionArgs will use
String selection = "City =? ";
In this case, we must assign the value String [] selectionArgs = {"Beijing"} In selectionArgs "};
That is to say, the string in selectionArgs is the variable corresponding to the question mark in selection. In fact, the filtering condition City in selection can be dynamically assigned, rather than being written to the program. During query () execution, the strings in selectionArgs are correctly escaped and replaced with the corresponding? To form a complete selection string. It is a bit like String. format ().
Obviously, the String groupBy parameter is the String corresponding to the group by parameter in the SQL statement. GROUP BY is used together with Aggregate Functions such as SUM. You can check the Usage Details on the Internet.
The String having parameter corresponds to the character String after the SQL statement HAVING and must be used together with the aggregate function.
The String orderBy parameter corresponds to the String following the SQL statement ORDER.
The limit parameter indicates the number of returned rows.
 
[Java]
DatabaseHelper dbHelper = new DatabaseHelper (SQLiteActivity. this, "test_mars_db ");
SQLiteDatabase db = dbHelper. getReadableDatabase ();
Cursor cursor = db. query ("user", new String [] {"id", "name"}, "id =? ", New String [] {" 1 "}, null );
While (cursor. moveToNext ()){
String name = cursor. getString (cursor. getColumnIndex ("name "));
System. out. println ("query --->" + name );
}

From sunset hut

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.