Original link: http://www.orlion.ga/603/
First, 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.
Sqliteopenhelper is an abstract class in which two abstract methods are OnCreate () and Onupgrade (), respectively, to implement the logic of creating and upgrading a database in these two methods
Sqliteopenhelper also has two very important example methods, Getreadabledatabase () and Getwritabledatabase (). Both methods can create or open an existing database (open directly if the database already exists, create one if it does not exist), 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 getwritabledatabase () will throw an exception.
There are two construction methods in Sqliteopenhelper that can be overridden, typically using a constructor that has fewer parameters. This construction method receives four parameters, the first of which is the context. The second is the name of the database. The third parameter allows us to return a custom cursor when querying the data, usually passing null. The fourth parameter is 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. The overridden OnCreate () method is also executed, so it is common to handle some of the logic that creates the table here.
Create a project Databasedemo, the new Mydatabasehelper class inherits from Sqliteopenhelper:
Package Ga.orlion.databasedemo;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.widget.Toast;
Import Android.database.sqlite.SQLiteOpenHelper;
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, "database created", Toast.length_short). Show ();
}
@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
}
}
The table statement is built in:
CREATE TABLE book (
ID Integer PRIMARY Key autoincrement,
Author text,
Price Real,
Pages Integer,
Name text)
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.
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.
Modify Activity_main.xml:
<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:
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
DBHelper = new Mydatabasehelper (This, "bookstore.db", NULL, 1);
Button button = (button) Findviewbyid (r.id.create_database);
Button.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (View v) {
Dbhelper.getwritabledatabase ();
}
});
Here we build a Mydatabasehelper object in the OnCreate () method, and specify the database name as Bookstore.db through the constructor's parameters, the version number is specified as 1, and then in the Create The Getwritabledatabase () method is called in the Click event of the Database button. So when the first click on the Create Database button, it will detect that the current program does not have the bookstore.db, so the database will be created and call Mydatabasehelper in the OnCreate () method, so The Book 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.
Next we use the ADB shell to view the creation of the database and the table, the ADB tool comes with the Android SDK, which can be used to debug the phone or emulator connected to the computer, which is stored in the Platform-tools directory of the SDK. Add this directory to the environment variable first. Then enter "adb shell" in the console, then use the "CD" command to enter the/data/data/ga.orlion.databasedemo/databases/directory, using LS to view all the files will see two files, One is the bookstore.db we created, and the other bookstore.db-journal is the temporary log file that is generated for the database to support transactions, typically the size of the file is 0. Next we open the database through the Sqlite3 command, only need to enter sqlite3 followed by the database name. This opens the Bookstore.db database, which can now be managed by the table of the database, which can be viewed by the ". Table" command.
, there are two tables, Android_meatdata is automatically generated for each database, and the other table book is created by us. You can also view their build statements by using the ". Schema" command.
Second, upgrade the database
If we want to add another table to the database that we created bookstore.db not be as simple as creating the first table book as it was in the OnCreate method, because our database has been created, onCreate () will no longer execute, So the Onupgrade () method is used.
You can change the Mydatabasehelper to:
Package Ga.orlion.databasedemo;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.widget.Toast;
Import Android.database.sqlite.SQLiteOpenHelper;
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");
public static final String create_category = "CREATE table CATEGORY ("
+ "ID integer primary key autoincrement,"
+ "Category_name text,"
+ "Category_code integer");
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);
Db.execsql (create_category);
Toast.maketext (Mcontext, "database created", Toast.length_short). Show ();
}
@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
Db.execsql ("drop table if exists book");
Db.execsql ("drop table if exists Category");
OnCreate (DB);
}
}
As you can see, we have executed two drop statements in the Onupgrade () method, and if we find that the Book table or category table already exists in the database, delete the two tables and then call the OnCreate () method to recreate them. Here, the existing table is deleted, because if the table is created when it is found to exist, the error will be directly.
The next step is to let the Onupgrade () method execute the fourth parameter received in the Sqliteopenhelper constructor method. It represents the version number of the current database, and it is now possible to have the Onupgrade () method executed by passing in a number larger than 1.
DBHelper = new Mydatabasehelper (This, "bookstore.db", NULL, 2);
Getting Started with Android (10) SQLite Create upgrade Database