6.3.1 Data Storage and Access - An Introduction to SQLite Databases
Category Android Basic Tutorial
Introduction to This Section:
>
In this section, we will continue to learn about the third method of Android data storage and access: the SQLite database. Unlike other SQL databases, we do not need to install a separate database software on the phone. The Android system has already integrated this database. We don't need to install and configure other database software (Oracle, MSSQL, MySQL, etc.), nor do we need to change ports and so on! That's all for the introduction, let's learn about this next.
1. Basic Concepts
1) What is SQLite? Why use SQLite? What are the features of SQLite?
>
Answer: Please listen to the detailed explanation by the little pig:
① SQLite is a lightweight relational database with fast computation speed and low resource consumption, making it very suitable for use on mobile devices. It not only supports standard SQL syntax but also follows the ACID (database transaction) principle. There is no need for an account, and it is very convenient to use!
② Previously, we learned to use files and SharedPreference to save data, but in many cases, files may not be effective, such as concurrent access in multi-threading; the app needs to handle potentially changing complex data structures, etc.! For example, bank deposits and withdrawals! Using the former two would seem very weak or cumbersome, and the emergence of the database can solve this problem, and Android has provided us with such a lightweight SQLite, why not use it?
③ SQLite supports five data types: NULL, INTEGER, REAL (floating point), TEXT (string text), and BLOB (binary object). Although there are only five, other data types such as varchar and char can also be saved; because SQLite has a major feature: you can save data of various data types in any field without worrying about the data type declared in the field, for example, you can store strings in an Integer type field, of course, except for the fields declared as INTEGER PRIMARY KEY, which can only store 64-bit integers! In addition, SQLite will ignore the data type information following the field name in the CREATE TABLE statement, such as the following statement will ignore the type information of the name field: CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))
Summary of features:
SQLite saves the database through files, a file is a database, the database contains multiple tables, the tables have multiple records, each record is composed of multiple fields, each field has a corresponding value, and each value can be specified with a type, or the type can also be unspecified (except for the primary key)
PS: By the way, the SQLite built into Android is version 3 of SQLite~
2) Several related classes:
>
Hehe, when learning something new, the most disliked thing is to encounter new terms, right? Let's first talk about the three classes we use when using the database:
SQLiteOpenHelper: An abstract class, we inherit this class, and then override the methods for creating and updating the database. We can also obtain the database instance or close the database through the object of this class!
SQLiteDatabase: Database access class: We can perform some add, delete, modify, and query operations on the database through the object of this class.
Cursor: A cursor, somewhat similar to the resultset in JDBC, the result set! It can be simply understood as a pointer pointing to a certain record in the database!
2. Creating the Database and Version Management Using the SQLiteOpenHelper Class
>
For apps involving databases, we can't manually create the database file for them, so we need to create the database table when the app is first used; and when our app is upgraded and the structure of the database table needs to be modified, it is necessary to update the database table at this time; for these two operations, Android provides two methods of SQLiteOpenHelper, onCreate ( ) and onUpgrade ( ) to achieve this.
Method Analysis:
>
onCreate(database): Generates the database table when the software is used for the first time.
onUpgrade(database,oldVersion,newVersion): It is called when the version of the database changes, usually only when the software is upgraded to change the version number, and the version of the database is controlled by the programmer. Suppose the current version of the database is 1, and due to business changes, the database table structure is modified, and then it is necessary to upgrade the software. When upgrading the software, it is protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = MainActivity.this; myDBHelper = new MyDBOpenHelper(mContext, "my.db", null, 1); bindViews(); }
private void bindViews() { btn_insert = (Button) findViewById(R.id.btn_insert); btn_query = (Button) findViewById(R.id.btn_query); btn_update = (Button) findViewById(R.id.btn_update); btn_delete = (Button) findViewById(R.id.btn_delete);
btn_query.setOnClickListener(this);
btn_insert.setOnClickListener(this);
btn_update.setOnClickListener(this);
btn_delete.setOnClickListener(this);
}
@Override public void onClick(View v) { db = myDBHelper.getWritableDatabase(); switch (v.getId()) { case R.id.btn_insert: ContentValues values1 = new ContentValues(); values1.put("name", "Hehe~" + i); i++; //Parameters in order are: table name, column name for forcing null values, data for one record db.insert("person", null, values1); Toast.makeText(mContext, "Insertion complete~", Toast.LENGTH_SHORT).show(); break; case R.id.btn_query: sb = new StringBuilder(); //Parameters in order are: table name, column names, where constraint, specific values for placeholders in where, columns for group by, further constraints //Specify the sort order for the query results Cursor cursor = db.query("person", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { int pid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); sb.append("id: " + pid + ": " + name + "\n"); } while (cursor.moveToNext()); } cursor.close(); Toast.makeText(mContext, sb.toString(), Toast.LENGTH_SHORT).show(); break; case R.id.btn_update: ContentValues values2 = new ContentValues(); values2.put("name", "Xixi~"); //Parameters in order are: table name, new values, where condition, and constraints. If the last two parameters are not specified, all rows will be changed db.update("person", values2, "name = ?", new String[]{"Hehe~2"}); break; case R.id.btn_delete: //Parameters in order are: table name, and where condition with constraints db.delete("person", "personid = ?", new String[]{"3"}); break; } }
5. Using SQL statements to operate the database
>
Of course, you may have already learned SQL and can write related SQL statements, and you don't want to use these APIs provided by Android. You can directly use the methods provided by SQLiteDatabase:
execSQL (SQL, Object[]): Executes SQL statements with placeholders, used for modifying the database content
rawQuery (SQL, Object[]): Performs SQL query operations with placeholders I also forgot to introduce the Cursor object and its related properties earlier, so here's a supplement: ——Cursor Object is somewhat similar to the ResultSet in JDBC, the result set! It is used in a similar way, providing the following methods to move the query result record pointer:
move (offset): Specifies the number of rows to move up or down, positive integers indicate moving down; negative numbers indicate moving up!
moveToFirst (): Moves the pointer to the first row, returns true if successful, which also indicates that there is data
moveToLast (): Moves the pointer to the last row, returns true if successful
moveToNext (): Moves the pointer to the next row, returns true if successful, indicating there are more elements!
moveToPrevious (): Moves to the previous record
getCount (): Gets the total number of data entries
isFirst (): Whether it is the first record
isLast (): Whether it is the last item
moveToPosition (int): Moves to a specific row
Example of using code:
1. Inserting data:
public void save(Person p)
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("INSERT INTO person(name,phone) values(?,?)",
new String[]{p.getName(),p.getPhone()});
}
2. Deleting data:
public void delete(Integer id)
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("DELETE FROM person WHERE personid = ?",
new String[]{id});
}
3. Modifying data:
public void update(Person p)
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL
6. Query Record Count:
```java
public long getCount()
{
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT (*) FROM person", null);
cursor.moveToFirst();
long result = cursor.getLong(0);
cursor.close();
return result;
}
PS : In addition to the above method of obtaining the number of entries, you can also use the cursor.getCount() method to get the number of data entries, but the SQL statement needs to be changed! For example, SELECT * FROM person;
Summary of This Section:
>
This section introduced the basic usage of Android's built-in SQLite, which is relatively simple. In the next section, we will explore some more advanced topics, such as SQLite transactions, how to handle data updates in the database, and methods for storing large binary files in the database! Alright, that's it for this section.
-1.0 Android Basic Tutorial for Beginners
-1.0.1 Latest Android Basic Tutorial Catalog for 2015
-1.1 Background and System Architecture Analysis
-1.2 Setting Up the Development Environment
-1.2.1 Developing Android APPs with Eclipse + ADT + SDK
-1.2.2 Developing Android APPs with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Installing Genymotion Emulator
-1.5.1 Git Tutorial on Basic Operations of Local Repositories
-1.5.2 Git: Setting Up Remote Repositories with GitHub
-1.6 How to Play with 9 (Jiu Mei) Images
-1.7 Interface Prototype Design
-1.8 Project-Related Analysis (Various Files, Resource Access)
-1.9 Android App Signing and Packaging
-1.11 Decompiling APK to Retrieve Code & Resources
-2.1 The Concept of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 TextView (Text Box) Detailed Explanation
-2.3.2 EditText (Input Box) Detailed Explanation
-2.3.3 Button (Button) and ImageButton (Image Button)
-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)
-2.3.7 ProgressBar (Progress Bar)
-2.4.1 ScrollView (Scroll View)
-2.4.2 Date & Time Components (Part 1)
-2.4.3 Date & Time Components (Part 2)
-2.4.5 Simple and Practical ListView
-2.4.6 Optimizing with BaseAdapter
-[2.4.7 ListView
4.4.2 A Further Exploration of ContentProvider – Document Provider
5.2.1 In-depth Discussion of Fragment Example – Implementation of Bottom Navigation Bar (Method 1)
5.2.2 In-depth Discussion of Fragment Example – Implementation of Bottom Navigation Bar (Method 2)
5.2.3 In-depth Discussion of Fragment Example – Implementation of Bottom Navigation Bar (Method 3)
5.2.4 In-depth Discussion of Fragment Example – Bottom Navigation Bar + ViewPager for Page Swiping
6.2 Data Storage and Access – SharedPreferences for Saving User Preferences
[6.3.1 An Introduction to SQLite Database
7.1.1 What to Learn in Android Network Programming and Study of HTTP Protocol
7.1.2 Learning About Android HTTP Request and Response Headers
[8.3.4 Paint API – Xfermode and PorterDuff Detailed Explanation (I)](android-
11.0 "2015 Latest Android Basic Tutorial" Completion Celebration~
12.2 DrySister Girl Viewing App (First Edition) — 2. Parsing Backend Data
12.4 DrySister Girl Viewing App (First Edition) — 4. Adding Data Caching (Incorporating SQLite)