SQLite is a lightweight relational database that works very fast, takes up less resources, and typically requires only hundreds of K of memory, making it ideal for use on mobile devices. SQLite not only supports the standard SQL syntax, but also follows the ACID transaction of the database, so you can quickly get on the floor with SQLite as long as you've used other relational databases before. and SQLite than the general database is much simpler, it does not even need to set the user name and password can be used. Android is the very powerful database embedded in the system, so that the local persistence of the function has a qualitative leap.
The file storage and sharedpreferences storage we have learned before is only applicable to save some simple data and key-value pairs, and when you need to store a lot of complex relational data, you will find that the two storage methods are difficult to cope with. For example, our mobile phone SMS program may have many sessions, each session contains a lot of information content, and most of the sessions may also correspond to a contact person in the phone book. It's hard to imagine how to use files or sharedpreferences to store data that is large and structurally complex. But you can do it using a database. So let's take a quick look at how the SQLite database in Android is used.
Create a database
Android in order to make it easier for us to manage the database, we specifically provide a Sqliteopenhelper helper class that allows you to create and upgrade the database very simply by using this class. Since there are good things to use directly, we naturally have to try, and I will introduce the basic usage of sqliteopenhelper.
First you need to know that Sqliteopenhelper is an abstract class, which means that if we want to use it, we need to create our own helper class to inherit it. There are two abstract methods in Sqliteopenhelper, namely OnCreate () and Onupgrade (), we must rewrite the two methods in our helper class, and then implement the logic of creating and upgrading the database separately in these two methods.
There are also two very important example methods in Sqliteopenhelper, Getreadabledatabase () and Getwritabledatabase (). Both of these methods can create or open an existing database (open directly if the database already exists, otherwise create a new database) and return an object that can read and write to the database. The difference is that when the database is not writable (such as disk space is full) the object returned by the Getreadabledatabase () method will open the database in a read-only manner, and the Getwritabledatabase () method will have an exception.
There are two construction methods in Sqliteopenhelper that can be overridden, typically using a less-parametric construction method. This construction method receives four parameters, the first parameter is the Context, this has nothing to say, must have it to operate the database. The second parameter is the database name, which is the name specified here when the database is created. The third parameter allows us to return a custom Cursor when querying the data, usually passing null. The fourth parameter represents the version number of the current database, which can be used to perform an upgrade operation on a database. Once the instance of Sqliteopenhelper is built, the getreadabledatabase () or Getwritabledatabase () method is called to create the database, and the database file is stored in the/data/data/< The package name>/databases/directory.
At this point, the overridden OnCreate () method is also executed, so there is usually some logic to create the table here.
Let's follow the example to get a more intuitive understanding of Sqliteopenhelper's usage, and start with a new Databasetest project. Here we want to create a database named Bookstore.db, and then build a new book table in this database with the ID (primary key), author, price, number of pages, and title of the list. Create a database table of course still need to use the table statement, here is to test your SQL basic, the Book Table of the table statement is as follows:
CREATE TABLE book (
ID Integer PRIMARY key autoincrement, author text,
Price real, pages integer, name text)
As long as you have a little bit of knowledge about SQL, the above statement should be easy for you. SQLite does not have many miscellaneous data types like other databases, its data types are simple, integer denotes integer, real is floating point, text is type, and blob represents binary type. In addition, we used the primary key to set the ID column as the primary key, and the AutoIncrement keyword to indicate that the ID column is self-growing. You then need to execute the SQL statement in your code to complete the operation of creating the table. The new Mydatabasehelper class inherits from Sqliteopenhelper, and the code looks like this:
Public class Mydatabasehelper extends Sqliteopenhelper {
public static final String Create_book = "CREATE table book ("
+ "ID integer primary key autoincrement,"
+ "Author text,"
+ "Price Real,"
+ "pages integer,"
+ "Name text");
Private Context Mcontext;
Public Mydatabasehelper (Context context, String name, Cursorfactory factory, int version) {
Super (context, name, Factory, version);
Mcontext = context;
}
@Override
public void OnCreate (Sqlitedatabase db) {
Db.execsql (Create_book);
Toast.maketext (Mcontext, "Create succeeded", Toast.length_short). Show ();
}
@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
}
}
As you can see, we define the build statement as a string constant and then call the Sqlitedatabase Execsql () method in the OnCreate () method to execute the build statement and pop up a Toast prompt to create the success, This ensures that the Book table can be created successfully while the database is being created.
Now modify the code in Activity_main.xml as follows:
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "
android:orientation= "Vertical" >
<button android:id= "@+id/create_database" android:layout_width= "match_parent" android:layout_height= "Wrap_ Content "android:text=" Create database "/>
</LinearLayout>
The layout file is simple enough to include a button to create the database. Finally, modify the code in Mainactivity as follows:
public class Mainactivity extends Activity {
Private Mydatabasehelper DBHelper;
@Override
protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);
DBHelper = new Mydatabasehelper (This, "bookstore.db", NULL, 1); Button CreateDatabase = (button) Findviewbyid (r.id.create_database); Createdatabase.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Dbhelper.getwritabledatabase ();
}
});
}
}
Here we build a Mydatabasehelper object in the OnCreate () method, and the database name is specified as Bookstore.db by the constructor's parameters, the version number is specified as 1, and then it is called in the Click event of the Create database button. Getwritabledatabase () method. So when the first click on the Create Database button, it detects that the current program does not have the bookstore.db, so it will create the database and call Mydatabasehelper in the OnCreate () method, so that the book The table is created and then a Toast prompt is created to create the success.
When you click the Create Database button again, you will see that there are already bookstore.db databases, so it will not be created again.
Now you can run the code, click the Create Database button in the main interface of the program, as shown in result 6.11.
Figure 6.11
Both the Bookstore.db database and the Book table should be created successfully, because no Toast pops up when you click the Create Database button again. But back to the old question, how can we prove that they were created successfully? If you still use File Explorer, you can only see a bookstore.db file in the databases directory, and the Book table cannot be seen through the file explorer. So this time we're going to look at a different view, using the ADB shell to check the creation of databases and tables.
ADB is a debugging tool that comes with the Android SDK, which allows you to debug a phone or emulator connected directly to your computer. It is stored in the Platform-tools directory of the SDK, and if you want to use the tool on the command line, you need to configure its path to the environment variable first.
If you are using a Windows system, you can right-click my computer → properties → advanced → environment variables, then locate the Path in the system variable and click Edit to configure the Platform-tools directory, as shown in 6.12.
Figure 6.12
If you are using a Linux system, you can edit the. bash_profile file under your home path, and configure the Platform-tools directory to go in, as shown in 6.13:
Figure 6.13
Once you have configured the environment variables, you can use the ADB tool. Open the command line interface and enter the ADB shell, which will go to the console of the device, as shown in 6.14.
Figure 6.14
Then use the CD command to go to the/data/data/com.example.databasetest/databases/directory and use the LS command to view the files in that directory, as shown in 6.15.
Figure 6.15
There are two database files in this directory, one is the bookstore.db that we created, and the other bookstore.db-journal is the temporary log file that is generated to allow the database to support transactions, typically the size of this file is 0 bytes.
Next we need to use the SQLite command to open the database, just type sqlite3, followed by the database name, 6.16.
Figure 6.16
At this point, the BOOKSTORE.DB database has been opened and the tables in this database can now be managed. First look at what tables are currently in the database, type the. Table command, as shown in 6.17.
Figure 6.17
As you can see, there are two tables in the database, and the Android_metadata table is automatically generated in each database, regardless of it, and the other book table is what we created in Mydatabasehelper. It is also possible to view their built-in statements by using the. Schema command, shown in 6.18.
Figure 6.18
This proves that the Bookstore.db database and the Book table have indeed been created successfully. After you type the. exit or. Quit command to exit the editing of the database, and then type the exit command to exit the device console.
===================================================================================================
1, enter into the console, enter the ADB shell, into the command mode environment
2, Input: cd/data/data/
3, select your database file, such as my com.android.homework, enter the command: CD com.android.homework
4, you can use the Ls-l command to view the files in the current directory
5, Input: CD databases into the database file
6, Ls-l displays the database you created in your database
7, Sqlite3 info.db into the database of your choice
8,. Tables: View the table you built
9, select * FROM Table_name;s can view information for the entire table
10, use other SQL statements to further manipulate the table, noting that the SQL statement must end with a semicolon (;)
As shown in the following:
Android_ New Database