Android experience 4.3 -- SQLite database -- execSQL () and rawQuery () Methods

Source: Internet
Author: User

1. In addition to using files or SharedPreferences to store data, you can also choose to use the SQLite database to store data.

On the Android platform, an embedded relational database-SQLite is integrated. SQLite3 supports NULL, INTEGER, REAL (floating point number), TEXT (string TEXT), and BLOB (binary object) data types, although it supports only five types, sqlite3 actually accepts data types such as varchar (n), char (n), decimal (p, s, it is only converted to the corresponding five data types during operation or storage.

The biggest feature of SQLite is that you can save any type of data to any field, regardless of the Data Type declared in this column. For example, you can store strings in Integer fields, floating point numbers in Boolean fields, or date values in numeric fields. But there is one exception: the field defined as integer primary key can only store 64-bit integers. When saving data other than Integers to this field, an error will occur. In addition, when parsing the create table statement, SQLite ignores the data type information following the field name in the create table statement. For example, the following statement ignores the type information of the name field:

Create table person (personid integer primary key autoincrement, name varchar (20 ))

2. SQLite can parse most standard SQL statements, such:

Query statement: select * from table name where Condition Clause group by grouping clause having... order by sorting clause

For example, select * from person

Select * from person order by id desc

Select name from person group by name having count (*)> 1

Paging SQL is similar to mysql. The following SQL statement gets five records and skips the first three records: select * from Account limit 5 offset 3 or select * from Account limit 3, 5

Insert statement: insert into Table Name (Field List) values (Value List ). For example, insert into person (name, age) values ('chuanzhi ', 3)

Update statement: update table name: set field name = value: where Condition Clause. For example, update person set name = 'chuanzhi 'where id = 10

Delete statement: delete from table name where Condition Clause. For example, delete from person where id = 10

3. when writing database application software, we need to consider this problem: because the software we developed may be installed on mobile phones of hundreds of thousands of users. If the application uses the SQLite database, we must create the database table structure used by the application and add some initialization records when users use the software for the first time. In addition, we also need to update the data table structure during software upgrade. Then, how can we automatically create the database tables required by the application on the user's mobile phone when the user first uses or upgrades the software? We cannot manually create database tables on every mobile phone that requires the software to be installed? This requirement is required for every database application. Therefore, in the Android system, an abstract class named SQLiteOpenHelper is provided, which must be inherited before it can be used, it manages the database version to meet the previous requirements.

To manage database versions, the SQLiteOpenHelper class provides two important methods: onCreate (SQLiteDatabase db) and onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ), the former is used to generate a database table when you first use the software, and the latter is used to update the database table structure when you upgrade the software. When the getWritableDatabase () or getReadableDatabase () method of SQLiteOpenHelper is called to obtain the SQLiteDatabase instance used to operate the database, if the database does not exist, the Android system automatically generates a database and then calls onCreate () method. The onCreate () method is called only when the database is generated for the first time. In the onCreate () method, you can generate the database table structure and add the initialization data used by some applications. The onUpgrade () method is called when the database version changes. Generally, the version number needs to be changed during software upgrade. The database version is controlled by programmers, assume that the current database version is 1 and the database table structure is modified due to business changes. In this case, you need to upgrade the software to update the database table structure on your mobile phone, to achieve this goal, you can set the original database version to 2 (some people may ask if it is set to 3 rows? Of course, if you want to, set it to 100) and update the table structure in the onUpgrade () method. When the number of software version upgrades is large, you can use the onUpgrade () method to determine based on the original number and target version number, and then update the table structure and data.

Both the getWritableDatabase () and getReadableDatabase () methods can obtain a SQLiteDatabase instance used to operate the database. However, the getWritableDatabase () method opens the database in read/write mode. Once the disk space of the database is full, the database can only read but cannot write data. If the getWritableDatabase () method is used, an error occurs. The getReadableDatabase () method first opens the database in read/write mode. If the disk space of the database is full, it will fail to be opened. When the opening fails, it will continue to attempt to open the database in read-only mode.

4. Some code is as follows:

Public class DatabaseHelper extends SQLiteOpenHelper {

// The class is not instantiated. It cannot be used as a parameter of the parent class constructor and must be declared as static.

Private static final String name = "itcast"; // Database name

Private static final int version = 1; // database version

Public DatabaseHelper (Context context ){

// The third parameter CursorFactory specifies the factory class for obtaining a cursor instance during query execution. If it is set to null, it indicates that the default factory class is used.

Super (context, name, null, version );

}

@ Override public void onCreate (SQLiteDatabase db ){

Db.exe cSQL ("create table if not exists person (personid integer primary key autoincrement, name varchar (20), age INTEGER )");

}

@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){

Db.exe cSQL ("drop table if exists person ");

OnCreate (db );

}

}

The above onUpgrade () method deletes the database table on the user's mobile phone every time the database version changes, and then creates a new one. This is generally not possible in actual projects. The correct method is to consider that the data stored in the database will not be lost when updating the database table structure.

5. android provides a class named SQLiteDatabase, which encapsulates APIs for database operations. This class can be used to Create, query, and Update data) and Delete operations (CRUD ). For SQLiteDatabase learning, we should master the execSQL () and rawQuery () methods. The execSQL () method can be used to execute SQL statements with changing behaviors such as insert, delete, update, and CREATE TABLE. The rawQuery () method can be used to execute select statements.

ExecSQL () method example:

SQLiteDatabase db = ....;

Db.exe cSQL ("insert into person (name, age) values ('chuanzhi pods', 4 )");

Db. close ();

When you execute the preceding SQL statement, a record is added to the person table. In actual application, the parameter values of the "Chuan Zhi podcast" in the statement are provided on the user input interface, if you splice the content entered by the user into the preceding insert statement as is, when the content entered by the user contains single quotes, the assembled SQL statement will have a syntax error. To solve this problem, you need to escape single quotes, that is, convert single quotes into two single quotes. In some cases, users often enter special SQL symbols such as "&". To ensure that the SQL statement syntax is correct, these special SQL symbols in the SQL statement must be escaped, obviously, it is cumbersome to do this for each SQL statement. The SQLiteDatabase class provides an overloaded execSQL (String SQL, Object [] bindArgs) method. This method can solve the problem mentioned above, this method supports using placeholder parameters (?). Example:

SQLiteDatabase db = ....;

Db.exe cSQL ("insert into person (name, age) values (?,?) ", New Object [] {" Chuanzhi podcast ", 4 });

Db. close ();

The first parameter of the execSQL (String SQL, Object [] bindArgs) method is the SQL statement, and the second parameter is the value of the placeholder parameter in the SQL statement, the order of parameter values in the array must correspond to the position of the placeholder.

6. rawQuery () of SQLiteDatabase is used to execute the select statement. The example is as follows:
SQLiteDatabase db = ....;

Cursor cursor = db. rawQuery ("select * from person", null );

While (cursor. moveToNext ()){

Int personid = cursor. getInt (0); // obtain the value of the first column. The index of the first column starts from 0.

String name = cursor. getString (1); // obtain the value of the second column

Int age = cursor. getInt (2); // get the value of the third column

}

Cursor. close ();

Db. close ();

The first parameter of the rawQuery () method is the select statement. The second parameter is the value of the placeholder parameter in the select statement. If the select statement does not use a placeholder, this parameter can be set to null. An example of a select statement with placeholder parameters is as follows:

Cursor cursor = db. rawQuery ("select * from person where name like? And age =? ", New String [] {" % Chuanzhi % "," 4 "});

Cursor Is a result set Cursor used for Random Access to the result set. If you are familiar with jdbc, Cursor works very similar to the ResultSet in JDBC. You can use the moveToNext () method to move the cursor from the current row to the next row. If the last row of the result set has been moved, false is returned; otherwise, true is returned. In addition, Cursor also has the commonly used moveToPrevious () method (used to move the Cursor from the current row to the previous row. If the first row of the result set has been moved, the return value is false; otherwise, the return value is true), moveToFirst () method (used to move the cursor to the first row of the result set. If the result set is empty, the return value is false; otherwise, it is true) and moveToLast () method (used to move the cursor to the last row of the result set. If the result set is empty, the return value is false. Otherwise, the return value is true ).

7. Code of the test method:

Package com. family. test;

 

Import java. util. List;

Import com. family. domain. Person;

Import com. family. service. DBOpenHelper;

Import com. family. service. PersonService;

Import android. test. AndroidTestCase;

Import android. util. Log;

 

Public class TestDB extends AndroidTestCase {

Public void testCreateDB () throws Exception {

DBOpenHelper dbOpen = new DBOpenHelper (getContext ());

DbOpen. getWritableDatabase ();

}

Public void testSave () throws Exception {

PersonService ps = new PersonService (getContext ());

For (int I = 0; I <20; I ++ ){

Person person = new Person ("zhangsan" + I, 21, "12345678900" + I );

Ps. save (person );

}

}

Public void testDelete () throws Exception {

PersonService ps = new PersonService (getContext ());

Ps. delete (2 );

}

Public void testUpdate () throws Exception {

PersonService ps = new PersonService (getContext ());

Person person = ps. find (1); // find (1): id 1 is the first parameter.

Person. setName ("Li Bingbing ");

Ps. update (person );

}

Public void testFind () throws Exception {

PersonService ps = new PersonService (getContext ());

Person person = ps. find (1 );

Log. I ("PersonTest", person. toString ());

}

Public void testGetScrollData () throws Exception {

PersonService ps = new PersonService (getContext ());

List <Person> persons = ps. getScrollData (0, 5 );

For (Person person: persons ){

Log. I ("PersonTest", person. toString ());

}

}

Public void testCount () throws Exception {

PersonService ps = new PersonService (getContext ());

Long result = ps. getCount ();

Log. I ("PersonTest", result + "");

}

}

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.