Android uses SQLiteDatabase to operate SQLite database Android uses SQLiteDatabase

Source: Internet
Author: User

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 is used to execute select statements.
ExecSQL () method example:
1 SQLiteDatabase db = ....;

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

3 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:
1 SQLiteDatabase db = ....;

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

3 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.
RawQuery () of SQLiteDatabase is used to execute select statements. The example is as follows:
1 SQLiteDatabase db = ....;

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

3 while (cursor. moveToNext ()){

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

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

6 int age = cursor. getInt (2); // obtain the value of the third column

7}

8 cursor. close ();

9 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:
1 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 ).

In addition to the execSQL () and rawQuery () methods described earlier, SQLiteDatabase also provides operation methods for adding, deleting, updating, and querying: insert (), delete (), update (), and query (). These methods are actually used by cainiao who are not familiar with SQL syntax. For programmers who are familiar with SQL syntax, execSQL () and rawQuery () are used directly () to add, delete, update, and query data.
The Insert () method is used to add data. The data of each field is stored using ContentValues. ContentValues is similar to MAP. Compared with MAP, it provides the put (String key, Xxx value) and getAsXxx (String key) methods for data access. key is the field name and value is the field value, xxx refers to various common data types, such as String and Integer.
1 SQLiteDatabase db = databaseHelper. getWritableDatabase ();

2 ContentValues values = new ContentValues ();

3 values. put ("name", "Chuanzhi podcast ");

4 values. put ("age", 4 );

5 long rowid = db. insert ("person", null, values); // return the row number of the newly added record, regardless of the primary key id.


No matter whether the third parameter contains data, the Insert () method will inevitably add a record. If the third parameter is Null, a record with Null values other than the primary key will be added. The Insert () method actually adds data by constructing an insert SQL statement. The second parameter of the Insert () method is used to specify the name of the null field. I believe you will be confused about this parameter, what is the role of this parameter? If the value of the third parameter is Null or the number of elements is 0, the Insert () method requires that you add a record with Null values in other fields except the primary key, to meet the needs of SQL syntax, the insert statement must be given a field name, for example, insert into person (name) values (NULL). If the field name is not given, the insert statement is like this: insert into person () values (), apparently this does not meet the standard SQL syntax. For field names, we recommend that you use a field other than the primary key. If an INTEGER type primary key field is used, after executing an insert statement similar to insert into person (personid) values (NULL, the value of this primary key field is not NULL. If the value of the third parameter is not Null and the number of elements is greater than 0, you can set the second parameter to null.

01 // use of the delete () method:

02 SQLiteDatabase db = databaseHelper. getWritableDatabase ();

03 db. delete ("person", "personid <? ", New String [] {" 2 "});

04 db. close ();

05 // The above code is used to delete records whose personid is less than 2 from the person table.

06

07 // use the update () method:

08 SQLiteDatabase db = databaseHelper. getWritableDatabase ();

09 ContentValues values = new ContentValues ();

10 values. put ("name", "Chuanzhi podcast"); // The key is the field name and the value is the value.

11 db. update ("person", values, "personid =? ", New String [] {" 1 "});

12 db. close ();

13 // The code above is used to change the value of the name field of the record whose personid is equal to 1 in the person table to "Chuanzhi podcast ".


The query () method splits the select statement into several components and serves as the input parameter of the method:
1 SQLiteDatabase db = databaseHelper. getWritableDatabase ();

2 Cursor cursor = db. query ("person", new String [] {"personid, name, age"}, "name like? ", New String [] {" % Chuanzhi % "}, null, null," personid desc "," 1, 2 ");

3 while (cursor. moveToNext ()){

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

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

6 int age = cursor. getInt (2); // obtain the value of the third column

7}

8 cursor. close ();

9 db. close ();


The above code is used to find records whose name field contains "intelligence" from the person table. matched records are sorted in descending order by personid. The first record is skipped for the sorted results and only two records are obtained.
Meanings of parameters in the query (table, columns, selection, selectionArgs, groupBy, having, orderBy, limit) method:
Table: table name. It is equivalent to the part after the select statement from keyword. For multi-table join queries, you can use commas to separate the two table names.
Columns: name of the column to be queried. It is equivalent to the part after the select keyword of the select statement.
Selection: the query Condition Clause, which is equivalent to the part after the where keyword of the select statement. The placeholder "?" can be used in the Condition Clause.
SelectionArgs: it corresponds to the placeholder value in the selection statement. The position of the value in the array must be the same as that of the placeholder in the statement. Otherwise, an exception occurs.
GroupBy: equivalent to the part after the select statement group by keyword
Having: equivalent to the part after the having keyword of the select statement
OrderBy: equivalent to the part after the select statement order by keyword, such as: personid desc, age asc;
Limit: Specifies the offset and the number of records obtained, which is equivalent to the part following the limit keyword of the select statement.

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.